blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
68043bd6a5099c622a478bb5977c69129ae6faea | tree3205/Projects | /cs636/parity_inclass.py | 1,961 | 3.546875 | 4 | import sys
class Parity(object):
def __init__(self, file):
self.file = file
def get_parity(self, c):
s = "{0:08b}".format(ord(c))
sum = 0
for b in s:
if b == '1':
sum += 1
return sum % 2
def encode(self, outfile):
"""Return encoded file and write to outfile."""
text = self.file.read()
for c in text:
s = "{0:08b}".format(ord(c))
parity = self.get_parity(c)
outfile.write(str(parity) + s[1:])
def get_ascii(self, byte_str):
data = byte_str[1:8]
value = int(data, 2)
return chr(value)
def decode(self):
"""Return decoded file as a string."""
text = self.file.read()
out_string = ''
while len(text) > 0:
if text[0] == '\n':
break
byte_str = text[0:8]
text = text[8:]
out_string += self.get_ascii(byte_str)
return out_string
def check(self):
"""Check the parity of an encoded file."""
rv = True
text = self.file.read()
while len(text) > 0:
if text[0] == '\n':
break
byte_str = text[0:8]
text = text[8:]
c = self.get_ascii(byte_str)
p = self.get_parity(c)
if str(p) != byte_str[0]:
rv = False
break
return rv
if __name__ == '__main__':
cmd = sys.argv[1]
if cmd == 'encode':
f = open(sys.argv[2])
out = open(sys.argv[3], 'w')
parity = Parity(f)
parity.encode(out)
f.close()
out.close()
elif cmd == 'decode':
f = open(sys.argv[2])
parity = Parity(f)
print(parity.decode())
f.close()
elif cmd == 'check':
f = open(sys.argv[2])
parity = Parity(f)
print(parity.check())
f.close()
|
f0363b56f458b3d0a4a993588b5ea624ac70e2bc | UsmanovTimur/Rock-Paper-Scissors | /localization/ru.py | 1,557 | 3.59375 | 4 | # coding:utf-8
from .localization import BaseLanguage
class RuLanguage(BaseLanguage):
"""Русский язык"""
@classmethod
def get_name(cls) -> str:
return "Русский"
def hello(self) -> str:
return """Добрового времени суток! Приятной игры)\nВыберите вариант:\n{}"""
def get_rock(self) -> str:
"""Получение имени камень"""
return "Камень"
def get_paper(self) -> str:
"""Получение имени бумаги"""
return "Бумага"
def get_scissor(self) -> str:
"""Получение имени ножниц"""
return "Ножницы"
def question(self) -> str:
"""вопрос пользователю"""
return "Ваш выбор?"
def again_question(self) -> str:
"""вопрос пользователю о повторе игры"""
return "Сыграем еще?"
def user_chose(self) -> str:
"""выбор пользователя"""
return "выбор пользователя"
def computer_chose(self) -> str:
"""выбор компьютера"""
return "выбор компьютера"
def win(self) -> str:
"""Победа"""
return "Вы победили!!!"
def lost(self) -> str:
"""Проигрыш"""
return "Вы проиграли!!!"
def equal(self) -> str:
"""ничья"""
return "Ничья!!!"
|
103db903d0cc102fe683fc5cc1a10959621d2bca | Timothy-Davis/NameSort | /Sorting.py | 2,651 | 4.375 | 4 | import sys
def sort_names(unsorted_names, sort_ption):
# This list will contain all the names whose first character falls outside of the English alphabet.
nonsortable_name_list = []
index = 0
while index < len(unsorted_names):
# First, strip extra characters (such as \n and spaces) off of each item in the list. This isolates the name.
unsorted_names[index] = unsorted_names[index].strip()
# If stripping the spaces and \n's from an entry leaves an empty string, we can remove it from the list.
if name_list[index] == '':
unsorted_names.remove(unsorted_names[index])
# If we do remove an entry from the list we can't increment index or else we'll skip next element
index -= 1
# If the first character of a name falls out of the ASCII range for English letters, we cannot sort the name.
elif ord((unsorted_names[index])[0]) < 65 or ord((unsorted_names[index])[0]) > 122:
nonsortable_name_list.append(unsorted_names[index])
unsorted_names.remove(unsorted_names[index])
# Since we remove the item from the name list, we need to make sure index doesn't increment.
index -= 1
# increment index to keep the loop moving forward
index += 1
# Now that pre-requisites are taken care of, we can sort the list by length alphabetically asc or desc
if sort_ption.lower() == "desc":
unsorted_names.sort(key=lambda x: x)
unsorted_names.sort(key=lambda x: (len(x)), reverse=True)
else:
unsorted_names.sort(key=lambda x: (len(x), x))
# If our list of non-sortable names has any values, we'll print it out as well.
if len(nonsortable_name_list) != 0:
print("The following names are not sortable: ", end='')
print(nonsortable_name_list)
if __name__ == "__main__":
if len(sys.argv) < 3:
print("There are too few arguments! Please pass a text file to sort. "
"The input should be (PATH)/Sorting.py (PATH)/input.txt (ASC OR DESC)")
sys.exit()
elif len(sys.argv) > 3:
print("There are too many arguments, assuming the first argument, sorting by length alphabetically ascending: ")
# The following lines will be responsible for reading the file.
name_file = open(sys.argv[1], "r", encoding='utf-8')
name_list = name_file.readlines();
sort_names(name_list, sys.argv[2])
# This loop prints the names out on the command line. Eventually will write to a text file.
for name in name_list:
print(name)
|
7da632e0af9a1429dcfc3d43d63b3c29a433c070 | plawanrath/Leetcode_Python | /wordBreakToGetAllCombos.py | 5,524 | 3.78125 | 4 | from typing import List
"""
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
wordBreak(s, wordDict)
return:
['cats and dog', 'cat sand dog']
Approach: This can be done with DFS. We start with the entire string s.
Then we go word by word in the wordDict to see if we can find one of the dordDict words in the string s
When we find one of the words in the wordDict, we start a recursive DFS in the reminder of the string if the reminder of the string is not already another valid word from the wordDict.
We will also maintain another list which will store all possible combos with valid words. So when we find a word in the wordDict we will simply add that with all the word combos to start making valid sentences.
This will continue until we have run our DFS through the entire string s. Finally we can join the resulting list of combos to get a list of valid word breaks.
res = {0: [['']]}
dfs(len(catsanddog)) = dfs(10) --> 1
for w in wordDict:
if s[10 - len(cat):i] = s[7:10] = dog == cat ? No
if s[10 - len(cats):i] = s[6:10] = ddog == cat ? No
... "and" ? No
... "sand" ? No
if s[10 - len(dog):i] = s[7:10] = dog == dog ? Yes
if 10 - len(dog) = 7 not in res ? Yes (its not)
dfs(10 - len(dog)) = dfs(10-3) = dfs(7) --> 2
for w in wordDict:
if s[7 - len(cat):7] = s[4:7] = and == cat ? No
... sand == cats ? No
... and == and ? Yes
if 4 not in res:
dfs(4) --> 3
for w in wordDict:
if s[4 - 3:4] = s[1:4] = ats == cat ? No
if s[4-4:4] = s[0:4] = cats == cats ? Yes
if 0 not in res ? No it is..
for prefix in res[0]:
prefix = ['']
res[4] = [['', 'cats']]
res = {0: [['']], 4: [['', 'cats']]}
if s[1:4] = ats == and ? No
if s[0:4] = cats == sand ? No
if s[1:4] = ats = dog ? No
dfs(4) -- > return
for prefix in res[7 - len(and)]:
1. prefix = ['', 'cats']
res[7] = [['', 'cats', 'and']]
res = {0: [['']], 4: [['', 'cats']], 7: [['', 'cats', 'and']]}
... s[sand] == sand ? Yes
if 7 - len(sand) = 3 not in res ?:
dfs(3) --> 4
for w in wordDict:
if s[3 - len(cat):3] = s[0:3] = cat == cat ? Yes
if 3 - len(cat) = 0 not in res ? Yes it is..
for prefix in res[0]:
prefix = ['']
res[3] = [['', 'cat']]
res = {0: [['']], 3: [['', 'cat']], 4: [['', 'cats']], 7: [['', 'cats', 'and']]}
if s[3 - len(cats):3] = s[-1:3] = '' == cats ? No
... s[0:3] == and ? No
... s[-1:3] == sand ? No
... s[0:3] == dog ? No
dfs(3) --> return
for prefix in res[7 - len(sand)] = res[3]:
1. prefix = ['', 'cat']
res[7] = [['', 'cats', 'and'], ['', 'cat', 'sand']]
res = {0: [['']], 3: [['', 'cat']], 4: [['', 'cats']], 7: [['', 'cats', 'and'], ['', 'cat', 'sand']]}
... s[7 - len(dog):7] = s[4:7] = and == dog ? No
dfs(7) --> return
for prefix in res[10 - len(dog)] = res[7]:
1. prefix = ['', 'cats', 'and']
res[10] = [['', 'cats', 'and', 'dog']]
2. prefix = ['', 'cat', 'sand']
res[10] = [['', 'cats', 'and', 'dog'], ['', 'cat', 'sand', 'dog']]
res = {0: [['']], 3: [['', 'cat']], 4: [['', 'cats']], 7: [['', 'cats', 'and'], ['', 'cat', 'sand']], 10: [['', 'cats', 'and', 'dog'], ['', 'cat', 'sand', 'dog']]}
return
for words in res[10]:
1. ['', 'cats', 'and', 'dog']
" ".join(word[1:]) = 'cats and dog'
2. ['', 'cat', 'sand', 'dog']
" ".join(word[1:]) = 'cat sand dog'
"""
from collections import defaultdict
def wordBreak(s: str, wordDict: List[str]) -> List[str]:
# recursion with memorization O(N^3) - Loop inside recusrion and also substring.
res = defaultdict(list)
res[0] = [['']] # Where key remembers the index from which the split happened i.e. memorization and value is a list of list of word combinations
def dfs(i):
if i < 0:
return
for w in wordDict:
if s[i - len(w):i] == w:
if i - len(w) not in res:
dfs(i - len(w))
for prefix in res[i - len(w)]:
res[i].append(prefix + [w])
dfs(len(s))
return [" ".join(words[1:]) for words in res[len(s)]] |
6fadc2a655e605c8f2a2905c99a6fd73f872992d | chenxu0602/LeetCode | /2552.count-increasing-quadruplets.py | 835 | 3.5 | 4 | #
# @lc app=leetcode id=2552 lang=python3
#
# [2552] Count Increasing Quadruplets
#
# @lc code=start
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
# Specifically, We use dp[j] stores the count of all valid triplets (i, j, k) that satisfies i < j < k and nums[i] < nums[k] < nums[j] and using the current index number as the role j.
# Time complexity: O(n^2)
# Space complexity: O(n)
n = len(nums)
dp = [0] * n
ans = 0
for j in range(n):
prev_small = 0
for i in range(j):
if nums[i] < nums[j]:
prev_small += 1
ans += dp[i]
elif nums[i] > nums[j]:
dp[i] += prev_small
return ans
# @lc code=end
|
8e066f76ac7506e112574510f617327927e0fc24 | lldenisll/learn_python | /aulas/bubblesort1.py | 642 | 3.609375 | 4 | class ordenador:
def bolha(self, lista):
fim = len(lista)
for i in range(fim-1, 0, 1):
for j in range(i):
if lista[j]>lista[j+1]:
lista[j], lista[j+1] = lista[j+1], lista[j]
return lista
print(lista)
def ordenada(self,lista):
fim = len(lista)
for i in range(fim - 1):
posicao_do_minimo = i
for j in range(i + 1, fim):
if lista[j] < lista[posicao_do_minimo]:
posicao_do_minimo = j
lista[i], lista[posicao_do_minimo] = lista[posicao_do_minimo], lista[i]
|
5174b45a4744d830fe4e5d7938ef951208a06be2 | Sulorg/Python | /Self-taught-programmer-Althoff/ООП2.py | 1,112 | 4.03125 | 4 | #Задание1
class Shape():
def what_am_i(self):
print("Я - фигура.")
class Square(Shape):
square_list = []
def __init__(self, s1):
self.s1 = s1
self.square_list.append(self)
def calculate_perimeter(self):
return self.s1 * 4
def what_am_i(self):
super().what_am_i()
print("Я - фигура.")
a_square = Square(29)
print(Square.square_list)
another_square = Square(93)
print(Square.square_list)
#Задание2
class Shape():
def what_am_i(self):
print("Я - фигура.")
class Square(Shape):
square_list = []
def __init__(self, s1):
self.s1 = s1
self.square_list.append(self)
def calculate_perimeter(self):
return self.s1 * 4
def what_am_i(self):
super().what_am_i()
print("Я - фигура.")
def __repr__(self):
return "{} на {} на {} на {}".format(self.s1, self.s1, self.s1, self.s1)
a_square = Square(29)
print(a_square)
#Задание3
def compare(obj1, obj2):
return obj1 is obj2
print(compare("а", "б"))
|
13e0c7bd4f2f5c00f3797ee473c20d0fa3933bf7 | LeiShi1313/leetcode | /leetcode_py/109_convert_sorted_list_to_binary_search_tree.py | 1,098 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def build_list(l):
if not l:
return None
p = head = ListNode(l[0])
for val in l[1:]:
node = ListNode(val)
p.next = node
p = p.next
return head
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
return self.build(head, None)
def build(self, head, end):
if head == end:
return None
slow = fast = head
while fast != end and fast.next != end:
slow = slow.next
fast = fast.next.next
mid = TreeNode(slow.val)
mid.left = self.build(head, slow)
mid.right = self.build(slow.next, end)
return mid
if __name__ == '__main__':
print(Solution().sortedListToBST(build_list([-10,-3,0,5,9]))) |
ec05db60745e84bc30d6e822ad36867d0e42fb6b | Vlas7528/Tensor-Homework | /lesson-1/Циклический светофор.py | 535 | 3.984375 | 4 | while True:
print('Введите код сигнала светофора, где:\n\n 1 - Красный\n 2 - Жёлтый\n 3 - Зелёный\n\nДля выхода из программы введите 5')
color=int(input())
if color == 1:
print('Стой')
elif color == 2:
print('Ожидай смены сигнала')
elif color == 3:
print('Иди')
elif color == 5:
break
else:
print('Неправильный код сигнала светофора') |
2e372442369383963cc25059d2e83e25874168ee | wisteria2gp/my_reinfo | /DP/environment_demo.py | 1,857 | 3.546875 | 4 | import random
import numpy as np
from environment import Environment
class Agent():
def __init__(self, env):
self.actions = env.actions
def policy(self, state):
return random.choice(self.actions)
def main():
# Make grid environment.
grid = [
[0, 0, 0, 1],
[0, 9, 0, -1],
[0, 0, 0, 0]
]
env = Environment(grid)
agent = Agent(env)
#Total Number Of Episode
NumEp=5
# Try NumEp times game.
stepList=[]
rewardList=[]
for i in range(NumEp):
# Initialize position of agent.
state = env.reset()
total_reward = 0
done = False
# 追加 print
print("-----------PROCESS------------------")
print("START State:",state)
# 追加 変数step
step=0
while not done:
action = agent.policy(state)
#追加 print
print(action)
next_state, reward, done = env.step(action)
#追加print
print("Next:",next_state)
total_reward += reward
state = next_state
step+=1
print("------------------------RESULT-----------------------")
#総step
print("Step Sum =",step)
print("Episode {}: Agent gets {} reward.".format(i, total_reward))
stepList.append(step)
rewardList.append(total_reward)
print("\n\n ***************TOTAL RESULT*********************\n\n")
print("Average Step=",np.average(stepList))
print("Std of Step=",np.std(stepList))
print("StepList:",stepList)
print("\n")
np.set_printoptions(precision=2)
rewardList=np.array(rewardList)
print("Average Reward=",np.average(rewardList))
print("Std of Reward=",np.std(rewardList))
print("RewardList:",rewardList)
if __name__ == "__main__":
main()
|
fb3b4528e47e29dd0eadf29668544dbcafedaf05 | cmok1996/helpme | /Python/tutorial/inheritance.py | 649 | 3.796875 | 4 | class Pet :
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(f"I am {self.name} and I am {self.age} years old")
def speak(self):
print("I dont know how to speak")
class Cat(Pet):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
print("Meow")
def show(self):
print(f"I am {self.name} and I am {self.age} years old and I am {self.color}")
class Dog(Pet):
def speak(self):
print("Woof")
p = Pet("Chris", 24)
p.speak()
c = Cat("Chris", 24, "blue")
c.show()
|
0694a4b9cb9ca4227ce79b7fc13613beb4ebeec6 | furu8/fizzbuzz | /test.py | 677 | 3.8125 | 4 | """
このファイルに解答コードを書いてください
"""
import pandas as pd
def read_text(path):
df = pd.read_table(path, sep=':', names=['num', 'str'])
return df
def main(df, m):
df = df.dropna()
df['num'] = df['num'].astype(int)
df['rem'] = m % df['num']
ans_df = df.loc[df['rem']==0]
ans_df = ans_df.sort_values('num')
ans = ''
for s in ans_df['str'].values:
ans += s
if not ans:
print(m)
else:
print(ans)
if __name__ == "__main__":
path = 'input.txt'
# path = 'sample1.txt'
# path = 'sample2.txt'
df = read_text(path)
m = int(df['num'].tail(1))
main(df, m) |
19010144e413b86b91a81310bc075f411e171cc1 | qkreltms/problem-solvings | /기반알고리즘모음/버블정렬/직접구현.py | 184 | 3.84375 | 4 | def bubble(a):
for i in range(len(a)):
for j in range(len(a)-1):
if a[j] > a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print(a)
bubble([8,5,3,2,7,1])
|
bc5505841e734e2fdc1ea7eb232b9a01c9dbb9f8 | pythonmentor/webinaire-python-mvc-juin-2021 | /mynotes/models.py | 1,613 | 3.65625 | 4 | from datetime import datetime
class Note:
"""Représente une note prise par l'utilisateur."""
def __init__(self, title, content=None, notebook=None, tags=[]):
self.updated_datetime = None
self.title = title
self.content = content
self.created_datetime = datetime.now()
self.notebook = notebook
self.tags = []
self.add_tags(*tags)
@property
def title(self):
"""Titre de la note."""
return self._title
@title.setter
def title(self, new_title):
self._title = new_title
self.updated_datetime = datetime.now()
def add_tags(self, *tags):
"""Ajouter un ou plusieurs tags à la note."""
for tag in tags:
tag = Tag(tag)
tag.add_note(self)
self.tags.append(tag)
def move(self, new_notebook):
"""Déplacer la note dans un autre notebook."""
self.notebook = new_notebook
def __repr__(self):
return f"Note(title={self.title})"
class Notebook:
def __init__(self):
self.title = None
self.notes = []
self.created_datetime = None
self.updated_datetime = None
def create_note(self):
pass
def search(self, text):
pass
def search_content(self, text):
pass
def __repr__(self):
return f"Notebook(title={self.title})"
class Tag:
def __init__(self, name):
self.name = name
self.notes = []
def add_note(self, note):
self.notes.append(note)
def __repr__(self):
return f"Tag(name={self.name})"
|
3fb4affcdc587d509aac886641c5005d6c39a7ae | tanisha03/Sem5-ISE | /SLL-finals/SEE/1a.py | 440 | 3.953125 | 4 | print("enter integers separated by space")
a=input().split() #separate elements by space
arr=[int(i) for i in a] #convert each to integer
print("Max :", max(arr))
print("Min :", min(arr))
print("enter element to be inserted")
i=int(input())
arr.append(i)
print("enter element to be deleted")
i=int(input())
arr.remove(i)
print("enter element to be searched")
i=int(input())
if(i in arr):
print("present")
else:
print("Not present")
|
f3f53439628ba0e2998b0ad6bed0d703dc249894 | FlavioFMBorges/exercicios_Python_Brasil | /leet code/1-two_sum.py | 1,186 | 3.984375 | 4 | """class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Dado um array de números inteiros e um alvo inteiro, retorna os índices dos dois números de forma que eles se somam ao alvo.
Você pode presumir que cada entrada teria exatamente uma solução e não pode usar o mesmo elemento duas vezes.
Você pode retornar a resposta em qualquer ordem.
1 - pegar os numeros para a lista
2 - percorrer a lista e ver qual numero somado que da o valor do alvo
3 - guardar o valor do indice em duas variaveis
4 - retornar o valor dos indices
aprender tabela hash para este proble
nums = int(input("Write integers numbers: "))
lista de tamanho máximo(ver vídeos de entrevista)
"""
def twoSum():
nums = [2, 7, 11, 15]
target = 9
list = []
for number in nums:
print(nums.index(number))
list.append(nums.index(number))
return print(list)
twoSum() |
8153ae422acf80c01f70d900daf5e9504e81844b | riverszxc/riverplum | /pkm/lbld/141.环形链表.py | 2,054 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=141 lang=python3
#
# [141] 环形链表
#
# https://leetcode.cn/problems/linked-list-cycle/description/
#
# algorithms
# Easy (51.49%)
# Likes: 1634
# Dislikes: 0
# Total Accepted: 857.9K
# Total Submissions: 1.7M
# Testcase Example: '[3,2,0,-4]\n1'
#
# 给你一个链表的头节点 head ,判断链表中是否有环。
#
# 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos
# 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
#
# 如果链表中存在环 ,则返回 true 。 否则,返回 false 。
#
#
#
# 示例 1:
#
#
#
#
# 输入:head = [3,2,0,-4], pos = 1
# 输出:true
# 解释:链表中有一个环,其尾部连接到第二个节点。
#
#
# 示例 2:
#
#
#
#
# 输入:head = [1,2], pos = 0
# 输出:true
# 解释:链表中有一个环,其尾部连接到第一个节点。
#
#
# 示例 3:
#
#
#
#
# 输入:head = [1], pos = -1
# 输出:false
# 解释:链表中没有环。
#
#
#
#
# 提示:
#
#
# 链表中节点的数目范围是 [0, 10^4]
# -10^5 <= Node.val <= 10^5
# pos 为 -1 或者链表中的一个 有效索引 。
#
#
#
#
# 进阶:你能用 O(1)(即,常量)内存解决此问题吗?
#
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# @lc code=end
|
d91c53a7c51168dcbe16df8900ffe667e84586ad | vnetserg/algorithms | /greedy/task3.py | 859 | 3.890625 | 4 | #!/usr/bin/env python3
'''
https://www.hackerrank.com/challenges/luck-balance
'''
def max_luck(max_loses, contests):
'''
Вернуть максимальное количество удачи, которое Лена может иметь
после окончания всех контестов.
Параметры:
max_loses - максимальнок число важных контестов,
которые Лена может проиграть;
contests - список кортежей (luck_balance, is_important)
'''
return 0
def main():
n_contests, max_loses = [int(x) for x in input().split()]
contests = [[int(x) for x in input().split()] for _ in range(n_contests)]
print(max_luck(max_loses, contests))
if __name__ == "__main__":
main()
|
9e113bf9dc7282ef12eec70e90df0b95fd30313b | mkirwa/Triangles | /triangle1.py | 129 | 3.65625 | 4 | #!usr/bin/python
from __future__ import print_function
for i in range(1,10):
for j in range(1,i):
print('#', end='')
print()
|
02c5db64c0443842315bd182d92dd1d95bac0dfe | ivopascal/Epistemic_Kwartet | /brain.py | 9,904 | 4.03125 | 4 | import deck
class Known_player:
'''
The Known_player class is distinctly different from the Player class.
A Known_player here is the representation of
a participant that exists in the brain.
You can therefore not interact with a Known_player,
but you can store your knowledge about that player here.
E.g. in this class I store that Known_player2 has card <8,3>,
then I can ask Player2 for card <8,3>
'''
def __init__(self, id, certainCards=None, certainNotCards=None):
self.id = id
self.certainCards = list()
self.certainNotCards = list()
self.knownKinds = list()
self.number_of_cards = 13
if certainCards is not None:
self.certainCards.extend(certainCards)
if certainNotCards is not None:
self.certainNotCards.extend(certainNotCards)
# Removes all cards of this kind from the Known_player
# After this it should be known that
# the Known_player does not hold any card of this kind
def remove_kind(self, kind):
kindSet = [deck.Card(kind, value) for value in range(4)]
for card in self.certainCards:
if card in kindSet:
self.certainCards.remove(card)
self.number_of_cards -=1
#removes a card from player
def card_taken(self, card):
self.exclude_card(card)
self.number_of_cards -=1
#When a card has been given, it needs to be added in certaincards and removed from certainnotcards
def card_given(self, card):
if card not in self.certainCards:
self.certainCards.append(card)
self.number_of_cards +=1
if card in self.certainNotCards:
self.certainNotCards.remove(card)
if card.kind not in self.knownKinds:
self.knownKinds.append(card.kind)
# Player cannot have card because it is somewhere else
def exclude_card(self, card):
if card in self.certainCards:
self.certainCards.remove(card)
if card not in self.certainNotCards:
self.certainNotCards.append(card)
if card.kind in self.knownKinds:
self.knownKinds.remove(card.kind)
#keep track of which card types are owned
def owns_card_of_type(self, card):
self.knownKinds.append(card.kind)
class Brain:
'''
The Brain class is intended as the knowledge center of a player.
Where the Player class handles the actions that a player may execute,
the brain class holds the knowledge that a player may have.
'''
# Make sure to pass cards by value with [:] !
# If cards not passed by value mutations outside the brain
# will also occur inside the brain.
def __init__(self, id, cards, nkinds):
self.known_players = list()
self.known_cards_number = list()
#for counting the cards
self.known_cards_number.append(13)
self.known_cards_number.append(13)
self.known_cards_number.append(13)
self.known_cards_number.append(13)
self.removed_kinds = list()
self.nkinds = nkinds
self.cards = cards
self.id = id
#print(self.cards)
# Let's the brain become aware that an opponent exists
# This allows it to keep track of how many components there are
def intro_opponent(self, id):
self.known_players.append(Known_player(id, certainNotCards=self.cards))
# Tells the brain that a Kind is removed from the game
# This does not actually remove any cards,
# it only removes knowledge of cards
def remove_kind(self, kind, id):
self.removed_kinds.append(kind)
if id == self.id:
for value in range(4):
self.cards.remove(deck.Card(kind, value))
for known_player in self.known_players:
known_player.remove_kind(kind)
# Returns all Kinds that have not yet been removed from the game
def get_valid_kinds(self):
return list(set(range(self.nkinds)) - set(self.removed_kinds))
# Check whether the player has a full set of a given Kind
# and remove it if he does
def checkSingleKind(self, kind):
for val in range(4):
card = deck.Card(kind, val)
if card not in self.cards:
return
return kind
# Check all Kinds to see if the player has any full sets of any Kind
def checkAllKinds(self):
full_kinds = list()
for kind in range(self.nkinds):
r = self.checkSingleKind(kind)
if r is not None:
full_kinds.append(r)
return full_kinds
# Learn that a card was taken from giver
# Determine who had that card and remove it from the mental model of them
def card_taken(self, card, giver):
if giver == self.id:
self.cards.remove(card)
else:
for known_player in self.known_players:
if known_player.id == giver:
known_player.card_taken(card)
else:
known_player.exclude_card(card)
# Learn that a card was given to a player
# Determine the player who received the card and add the card to the mental
# model of them.
def card_given(self, card, receiver):
if receiver == self.id:
self.cards.append(card)
else:
for known_player in self.known_players:
if known_player.id == receiver:
known_player.card_given(card)
# Tells the player that an opponent does not own a given card
def exclude_card(self, card, opponent_id):
if opponent_id == self.id:
return
else:
for known_player in self.known_players:
if known_player.id == opponent_id:
known_player.exclude_card(card)
#add cards to the card types they own list
def owns_card_of_type(self, card, receiver):
if receiver == self.id:
return
else:
for known_player in self.known_players:
if known_player.id == receiver:
known_player.owns_card_of_type(card)
# Find who I already know has a certain card
def find_holder(self, card):
if card in self.cards:
return [self.id]
for known_player in self.known_players:
if card in known_player.certainCards:
return [known_player.id]
return [known_player for known_player in self.known_players
if card not in known_player.certainNotCards]
#return a list with all card types the player owns
def get_owned_kinds(self):
owned_kinds = list()
for card in self.cards:
if card.kind not in owned_kinds:
owned_kinds.append(card.kind)
return owned_kinds
#returns a list with all cards a player can request + their owner
def get_requestable_cards(self):
owned_kinds = self.get_owned_kinds()
requestable_cards = list()
for known_player in self.known_players:
for card in known_player.certainCards:
if card.kind in owned_kinds:
requestable_cards.append((card, known_player.id))
return requestable_cards
#returns the number of cards the player can request
def get_number_of_requestable_cards(self, opponent):
requestable_cards = list()
for known_player in self.known_players:
if known_player is opponent:
for card in known_player.certainCards:
if card.kind in owned_kinds:
requestable_cards.append((card, known_player.id))
return len(requestable_cards)
#Checks for a specific card and opponent if they have this card in certainCards
def certain_cards(self, opponent, card):
for known_player in self.known_players:
if known_player.id is opponent:
if card in known_player.certainCards:
return 1
else:
return 0
#Checks for a specific card and opponent if they have this card in certainNotCards
def certain_not_cards(self, opponent, card):
for known_player in self.known_players:
if known_player.id is opponent:
if card in known_player.certainNotCards:
return 1
else:
return 0
#Checks for a specific card type and opponent if they have this card in knownKinds
def owns_kind(self, opponent, card):
for known_player in self.known_players:
if known_player.id is opponent:
if card in known_player.knownKinds:
return 1
else:
return 0
#adds card to knowledge for single player after infering the position of the card
def add_card_to_knowledge(self, opponent, card):
for known_player in self.known_players:
if known_player.id == opponent:
known_player.card_given(card)
#Checks if a certain card is already in a certainCards list
def check_if_in_list(self, card):
owned_kinds = self.get_owned_kinds()
requestable_cards = list()
for known_player in self.known_players:
if card in known_player.certainCards:
return True
#returns the card combined with the owner, given only a card
def return_card_in_list(self, card):
owned_kinds = self.get_owned_kinds()
requestable_cards = list()
for known_player in self.known_players:
if card in known_player.certainCards:
for cards in known_player.certainCards:
if cards == card:
return (cards, known_player.id)
|
75d26236f7a0f532b4ae996d75ad6703de19543c | ji0859/Algorithm | /programmers/level1/서울에서 김서방 찾기.py | 168 | 3.5 | 4 | def solution(seoul):
answer = ''
for i in seoul:
if i == "Kim":
answer = "김서방은 "+str(seoul.index(i))+"에 있다"
return answer
|
7065171cd6b55d9db273c61d40ed34fc949943c8 | cjduffett/Python-Projects | /Always Turn Left/Boundaries.py | 712 | 3.734375 | 4 | import sys
# ----------------------------------------------
# Boundaries of the maze; min/max x and y vals
# ----------------------------------------------
class Boundaries:
def __init__(self):
self.xmin = 0
self.ymin = 0
self.xmax = 0
self.ymax = 0
def getSize(self):
return int(abs(self.ymax - self.ymin) + 1), int(abs(self.xmax - self.xmin) + 1) # row, cols
def getRange(self):
return self.xmin, self.xmax, self.ymin, self.ymax
def printIt(self):
sys.stdout.write("(" + str(self.xmin) + ", " + str(self.xmax))
sys.stdout.write(", " + str(self.ymin) + ", " + str(self.ymax) + ")\n")
|
713e1f55f41ba169363ec5290320c98aaa7ab5f9 | r87007541/270201026 | /lab4/example5.py | 106 | 4.125 | 4 | n = int(input("Enter a Number :"))
factorial = 1
for x in range(1,n+1) :
factorial *= x
print(factorial) |
c96a63821c2542257ee4cb1ce548823b7be141cb | Theneaaaaaa/unit_seven | /d2_unit_seven_warmups.py | 183 | 3.84375 | 4 | name = "Guido van Rossum"
lowercase_name = name.lower()
print(lowercase_name)
index = name.index("v")
print(index)
print(name[10])
split_name = lowercase_name.split()
print(split_name)
|
086a9e15549e67a605196af485c36d6d0a3c874b | TuckerFerguson/py_DataScience | /numpy_methods/multiDimensionXOR_NumPy.py | 962 | 4.40625 | 4 | """
@author Tucker Ferguson
1/9/2020
Simulating 'XOR' on a 3D array, using the numpy library (array,shape,ones)
"""
import numpy as np
#3D array to preform 'XOR' operation on
my3dArray = np.array([
[[0,1,0],
[0,1,0],
[0,1,0]],
[[0,1,0],
[0,1,0],
[0,1,0]],
[[0,1,0],
[0,1,0],
[0,1,0]]
])
#Get the shape of the array to be inverted 'my3dArray'
shape = my3dArray.shape
#Next create an equal in dimensions array of integer values: 1 'onesArray'
onesArray = np.ones(shape,int)
#Using the logic below we effectively invert the array it can also be seen as an Xor
copyArray = my3dArray
my3dArray = (my3dArray - onesArray) * -1
print("{0}\n\n XOR \n\n{1}\n\n Equals \n\n{2}".format(copyArray,onesArray,my3dArray)) |
7c64176782af6f0b7d43ea061a21cfd5c02ff4bb | programmicon/teknowledge | /curriculum/07_game_02_circle_clash_2_DAYS/07_game_02_circle_clash_day_1/07_02_02_circle_clash_advanced.py | 3,641 | 4 | 4 | from tkinter import *
# the game data for the initial game state
def init():
data.playerX = 250
data.playerY = 550
data.circleX = 250
data.circleY = 0
data.gameOver = False
# events updating the game data
def keyPressed(event):
if event.keysym == "Right" and data.playerX < 550:
data.playerX += 5
elif event.keysym == "Left" and data.playerX > 0:
data.playerX -= 5
def moveCircle():
if not data.gameOver:
data.circleY += 10
# the game data updating the game state
def timerFired():
moveCircle()
if checkCollision(data.playerX, data.playerY,
data.circleX, data.circleY,
10, 50):
data.gameOver = True
if data.circleY > 600:
data.gameOver = True
def checkCollision(x1, y1, x2, y2, r1, r2):
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
return distance <= r1 + r2
# the game state updating what is drawn
def redrawAll(canvas):
canvas.create_oval(data.playerX - 10, data.playerY - 10,
data.playerX + 10, data.playerY + 10,
fill="red")
canvas.create_oval(data.circleX - 50, data.circleY - 50,
data.circleX + 50, data.circleY + 50, \
fill="yellow")
if data.gameOver:
canvas.create_text(300, 250, text="Game Over", font=" Arial 20")
# Challenge 2.1 - Make it so that at the top of the screen it says "Score: __"
# where the __ is a number that increases every time timerFired() happens.
# Challenge 2.2 - Make it so that every third time timerFired() happens a new
# circle is added to the top of the screen with random x position, color,
# and size.
# Suggested way to do this:
# 1. Make a data.timer variable that starts at 0 and increases by 1 every
# timerFired() and a data.circles variable that starts as [].
# 2. When data.timer gets to 3, reset it to 0 and call a new function
# createNewCircle().
# 3. Write createNewCircle() to append a tuple to data.circles of the
# format:
# (xCoordinate, yCoordinate, radiusSize, colorString)
# 4. In redrawAll(), loop over the data.circles list and draw each circle.
# 5. In timerFired(), every second, move each circle's yPosition down by
# 10 pixels.
# BONUS Challenge 2.3 - Make the game better with your own ideas!
# The coding world is now yours for the exploring :)
# ***** DO NOT MODIFY BELOW HERE ***** #
# animation setup code
class Struct(object): pass
data = Struct()
def run(width=600, height=600):
def redrawAllWrapper(canvas):
canvas.delete(ALL)
redrawAll(canvas)
canvas.update()
def keyPressedWrapper(event, canvas):
keyPressed(event)
redrawAllWrapper(canvas)
def timerFiredWrapper(canvas):
timerFired()
redrawAllWrapper(canvas)
# pause, then call timerFired again
canvas.after(data.timerDelay, timerFiredWrapper, canvas)
# Set up data and call init
data.width = width
data.height = height
data.timerDelay = 200 # milliseconds
init()
# create the root and the canvas
root = Tk()
canvas = Canvas(root, width=data.width, height=data.height)
canvas.pack()
# set up events
root.bind("<Key>", lambda event:
keyPressedWrapper(event, canvas))
timerFiredWrapper(canvas)
# and launch the app
root.mainloop() # blocks until window is closed
print("bye!")
run()
|
1992ba39499260d7b985a333d364e9cf7672c334 | ricknigel/machineLearningCookbook | /chapter1/recipe1-10.py | 550 | 3.9375 | 4 | # 1.10 ベクトル、行列の転置
# 問題
# ベクトルもしくは行列を転置したい。
import numpy as np
# 行列を作成
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]
])
# 行列を転置
print(matrix.T)
# 転置とは、
# 行列の各要素に対する列インデックスと行インデックスを入れ替えること。
# ベクトルの転置 以下の場合、転置できない。
print(np.array([1, 2, 3, 4, 5, 6]).T)
# 行ベクトルの転置
print(np.array([[1, 2, 3, 4, 5, 6]]).T)
|
8ca2ea1de6c297cfc06513a07bd18c14e4322c87 | mehransadeghi/Python_Stocks_2 | /stock.py | 6,551 | 3.5625 | 4 | import requests
from pyquery import PyQuery
from iex import Stock
from selenium import webdriver
MAX_TICKERS=110
class Tickers:
"""
A class to fetch all tickers and store them in a file tickers.txt
:type ticker_count: int
:param ticker_count: The number of tickers to get
"""
def __init__(self, n):
"""
Creates the variables associated with the class
:type n: int
:param n: The number of tickers to get
"""
self.ticker_count = n
def pull200ItemsURL(self):
"""
Clicks a button to make the webpage display 200 tickers
:return: The url to a page containing 200 ticker symbols
:rtype: string
"""
# Set up Chrome instance of this url
driver = webdriver.Chrome(executable_path='./chromedriver')
driver.get('http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQrender=download')
# Click on the 150 option in page size select so we can get all the symbols we need
page_size_select = driver.find_element_by_id('main_content_lstpagesize')
for page_size_option in page_size_select.find_elements_by_tag_name('option'):
if page_size_option.text == '200 Items Per Page':
page_size_option.click()
break
return driver.current_url
def __str__(self):
"""
:return: the number of tickers to grab from the url
:rtype: string
"""
return str(self.ticker_count)
def save_tickers(self, file_name='tickers.txt'):
"""
Writes ticker symbols to a file named tickers.txt
:type file_name: string
:param file_name: Name of the file in which to store the ticker symbols
:rtype: void
"""
if int(self.ticker_count) > MAX_TICKERS:
raise Exception("You need to give me a number less than or equal to 110!")
# Create request with 150 item url
request = requests.get(url=self.pull200ItemsURL())
parser = PyQuery(request.text)
table = parser("#CompanylistResults")
table_parser = PyQuery(table)
symbols = table_parser("h3")
symbol_list = [symbol for symbol in symbols.text().split()]
valid_tickers=[]
for ticker in (symbol_list):
try:
if len(valid_tickers) < int(self.ticker_count):
Stock(ticker).price()
valid_tickers.append(ticker)
print(ticker)
else:
break
except:
pass
f = open(file_name, "w")
for symbol in (valid_tickers):
f.write(symbol + '\n')
f.close()
import datetime
import time
import sqlite3
class Fetcher:
"""
A class to write all relevant information for the tickers in tickers.txt to a database
:type database_name: string
:param database_name: The name of the database to store the information in
:type time_lim: int
:param time_lim: The time, in seconds, to update the database
"""
def __init__(self, db, tl):
"""
Creates the variables associated with the class
:type db: string
:param db: The name of the database to store the information in
:type tl: int
:param tl: The time, in seconds, to update the database
"""
self.database_name = db
self.time_lim = tl
def update_ticker(self, ticker, conn, current_time, test=False):
"""
Creates a new row in the database for the specified ticker and time
:type ticker: string
:param ticker: The ticker to be inserted
:type conn:
:param conn: The connection to the database
:type current_time: datetime
:param current_time: The current time to be inserted
:rtype: void
"""
s=Stock(str(ticker))
ticker_info = Stock(ticker).quote()
c = conn.cursor()
values = "('{}', '{}', '{}', '{}', '{}', '{}', {}, {})".format(current_time, ticker, ticker_info['low'], ticker_info['high'], ticker_info['open'],ticker_info['close'],
ticker_info['latestPrice'], ticker_info['latestVolume'])
if(test):
test_file = open('test_fetch.txt', 'a+')
test_file.write(values+'\n')
test_file.close()
cmd = ' INSERT INTO StockData VALUES ' + values
c.execute(cmd)
conn.commit()
def fetch_all_data(self, ticker_file='tickers.txt', test=False):
"""
Waits until the start of the next minute and then writes the tickers from tickers.txt to a database
:type ticker_file: string
:param ticker_file: Name of the file in which the tickers are stored
:rtype: void
"""
currentDT = datetime.datetime.now()
endTime = currentDT + datetime.timedelta(seconds=int(self.time_lim))
if(currentDT < endTime):
conn = sqlite3.connect(self.database_name)
while currentDT < endTime:
print(currentDT, endTime)
fp = open(ticker_file)
# Calculate time to sleep until next minute starts
sleepTime = 60 - (datetime.datetime.now().second + datetime.datetime.now().microsecond / 1000000.0)
time.sleep(sleepTime)
current_time = self.two_digit_time(currentDT)
for ticker in fp:
self.update_ticker(ticker.strip(), conn, current_time, test)
fp.close()
currentDT = datetime.datetime.now()
def two_digit_time(self, currentDT):
"""
Formats the time that will be inserted into the database
:type currentDT: datetime
:param currentDT: The current time
:return: The time formatted as HH:MM
:rtype: string
"""
hour = currentDT.hour
minute = currentDT.minute
if minute < 10:
minute = '0' + str(minute)
else:
minute = str(minute)
if hour < 10:
hour = '0' + str(hour)
else:
hour = str(hour)
return('{}:{}'.format(hour, minute))
def __str__(self):
return 'time_limit = {}, database_name = {}'.format(self.time_lim, self.database_name)
class Query:
"""
A class to query the database for a certain time and ticker
:type database_name: string
:param database_name: The name of the database that information is stored in
:type time: string
:param time: The time to search for in the database
:type ticker: string
:param ticker: The ticker to search for in the database
"""
def __init__(self, db, t, tn):
"""
creates the variables associated with the class
:type db: string
:param db: The name of the database that information is stored in
:type t: string
:param t: The time to search for in the database
:type tn: string
:param tn: The ticker to for in the database
"""
self.database_name = db
self.time = t
self.ticker = tn
def print_info(self):
"""
Queries the database for a specific time and ticker
:rtype: void
"""
conn = sqlite3.connect(self.database_name)
c= conn.cursor()
cmd = ''' SELECT * FROM StockData WHERE Time=='{}' and Ticker=='{}' '''.format(self.time, self.ticker)
c.execute(cmd)
return(c.fetchone())
def __str__(self):
return 'time = {}, database_name = {}, ticker = {}'.format(self.time, self.database_name, self.ticker)
|
13cd84bc6498985615b191fe1eb977f007e6bf9a | serimj98/fundprog | /serimj@andrew.cmu.edu_hw9_4_handin.py | 10,382 | 3.59375 | 4 | # 15-112
# Name: Serim Jang
# Andrew ID: serimj
#################################################
# Hw9
#
# No iteration! no 'for' or 'while'. Also, no 'zip' or 'join'.
# You may add optional parameters
# You may use wrapper functions
#
#################################################
import cs112_f17_week9_linter
def almostEqual(x, y, epsilon = 10**-8):
return abs(x-y) < epsilon
##############################################
# Recursive questions
##############################################
# Returns the kth power of all numbers below and including n
def powerSum(n, k, current = 1):
if n <= 0: # when negative number, 0
return 0
if k < 0: # when negative number, 0
return 0
if current == n: # base case
return current**k
if current < n: # recursive case
return current**k + powerSum(n, k, current+1)
# Helper function to add squares of individual digits in the number
def sumOfSquaresOfDigits(x):
if x <= 0: # base case; adds nothing if reaches last digit
return 0
else: # recursive case; adds square of each digit
return (x%10)**2 + (sumOfSquaresOfDigits(x//10))
# Returns True if is a happy number
def isHappyNumber(x):
if x < 0:
return False
if x == 1: # definition of happy number
return True
if 1 < x < 10 and sumOfSquaresOfDigits(x) != 1: # base case
return False
else: # recursive case
return isHappyNumber(sumOfSquaresOfDigits(x))
# Evalutes prefix notation
def evalPrefixNotation(L):
if isinstance(L[0], int): # base case
return L.pop(0)
if isinstance(L[0], str): # recursive case
operator = L.pop(0)
if operator == '+':
return evalPrefixNotation(L) + evalPrefixNotation(L)
if operator == '-':
return evalPrefixNotation(L) - evalPrefixNotation(L)
if operator == '*':
return evalPrefixNotation(L) * evalPrefixNotation(L)
##############################################
# OOP questions
##############################################
class VendingMachine(object):
def __init__(self, bottles, cents):
self.bottles = bottles
self.bottleVar = "bottles"
self.originalCents = cents
self.cents = cents
self.paid = 0
self.left = cents
self.change = 0
def __hash__(self):
return hash(self.bottles)
return hash(self.cents)
def __repr__(self):
if self.bottles == 1: self.bottleVar = "bottle" # singular
else: self.bottleVar = "bottles" # plural
# when no cents, exact dollar amount; when cents, until the cent value
if self.originalCents % 100 == 0 and self.paid % 100 == 0:
return "Vending Machine:<" + "%s "%(self.bottles) + \
"%s"%(self.bottleVar) + "; $" + "%d"%(self.originalCents/100) +\
" each; $" + "%d"%(self.paid/100) + " paid>"
if self.originalCents % 100 == 0 and self.paid % 100 != 0:
return "Vending Machine:<" + "%s "%(self.bottles) + \
"%s"%(self.bottleVar) + "; $" + "%d"%(self.originalCents/100) +\
" each; $" + "%0.2f"%(self.paid/100) + " paid>"
if self.originalCents % 100 != 0 and self.paid % 100 == 0:
return "Vending Machine:<" + "%s "%(self.bottles) + \
"%s"%(self.bottleVar) + "; $" + "%0.2f"%(self.originalCents/100) +\
" each; $" + "%d"%(self.paid/100) + " paid>"
if self.originalCents % 100 != 0 and self.paid % 100 != 0:
return "Vending Machine:<" + "%s "%(self.bottles) + \
"%s"%(self.bottleVar) + "; $" + "%0.2f"%(self.originalCents/100) +\
" each; $" + "%0.2f"%(self.paid/100) + " paid>"
def __eq__(self,other):
# all numbers within the class VendingMachine should be equal
return isinstance(other, VendingMachine) and \
self.bottles == other.bottles and self.bottleVar == other.bottleVar \
and self.originalCents == other.originalCents and \
self.cents == other.cents and self.paid ==other.paid and \
self.left == other.left and self.change == other.change
def isEmpty(self):
if self.bottles != 0: # when no bottles, isEmpty
self.paid = 0
return False
else:
return True
def getBottleCount(self):
return self.bottles # number of bottles
def stillOwe(self):
if self.bottles == 0: # returns amount you paid if no bottles
self.left = self.originalCents
return self.originalCents
else: # if bottles exist, the money you still need to put in
return self.left
def insertMoney(self, insert):
self.left -= insert
self.paid += insert
if self.left == 0: # when you put in the full amount
self.cents = 0
self.bottles -= 1
self.left = self.originalCents
self.paid = 0
return ("Got a bottle!", self.change)
if self.bottles == 0: # when no bottles
return ("Machine is empty", insert)
if self.left < 0: # when you put in extra money
self.change = abs(self.left)
self.cents = self.change
self.bottles -= 1
self.left = self.originalCents
return ("Got a bottle!", self.change)
if self.left % 100 == 0: # when no cents, return exact dollar amount
return ("Still owe $" + "%d"%(int(self.left/100)), self.change)
else: # when cents, returns until the cent value
return ("Still owe $" + "%.2f"%(self.left/100), self.change)
def stockMachine(self, stock):
self.bottles += stock # adds bottles to the stock
#################################################
# Test Functions
#################################################
def testPowerSum():
print('Testing powerSum()...', end='')
assert(powerSum(4, 6) == 1**6 + 2**6 + 3**6 + 4**6)
assert(powerSum(0, 6) == 0)
assert(powerSum(4, 0) == 1**0 + 2**0 + 3**0 + 4**0)
assert(powerSum(4, -1) == 0)
print('Done!')
def testIsHappyNumber():
print('Testing isHappyNumber()...', end='')
assert(isHappyNumber(-7) == False)
assert(isHappyNumber(1) == True)
assert(isHappyNumber(2) == False)
assert(isHappyNumber(97) == True)
assert(isHappyNumber(98) == False)
assert(isHappyNumber(404) == True)
assert(isHappyNumber(405) == False)
print('Done!')
def testEvalPrefixNotation():
print('Testing evalPrefixNotation()...', end='')
assert(evalPrefixNotation([42]) == 42)
assert(evalPrefixNotation(['+', 3, 4]) == 7)
assert(evalPrefixNotation(['-', 3, 4]) == -1)
assert(evalPrefixNotation(['-', 4, 3]) == 1)
assert(evalPrefixNotation(['+', 3, '*', 4, 5]) == 23)
assert(evalPrefixNotation(['+', '*', 2, 3, '*', 4, 5]) == 26)
assert(evalPrefixNotation(['*', '+', 2, 3, '+', 4, 5]) == 45)
assert(evalPrefixNotation(['*', '+', 2, '*', 3, '-', 8, 7,
'+', '*', 2, 2, 5]) == 45)
print('Done!')
def testVendingMachineClass():
print("Testing Vending Machine class...", end="")
# Vending machines have three main properties:
# how many bottles they contain, the price of a bottle, and
# how much money has been paid. A new vending machine starts with no
# money paid.
vm1 = VendingMachine(100, 125)
assert(str(vm1) == "Vending Machine:<100 bottles; $1.25 each; $0 paid>")
assert(vm1.isEmpty() == False)
assert(vm1.getBottleCount() == 100)
assert(vm1.stillOwe() == 125)
# When the user inserts money, the machine returns a message about their
# status and any change they need as a tuple.
assert(vm1.insertMoney(20) == ("Still owe $1.05", 0))
assert(vm1.stillOwe() == 105)
assert(vm1.getBottleCount() == 100)
assert(vm1.insertMoney(5) == ("Still owe $1", 0))
# When the user has paid enough money, they get a bottle and
# the money owed resets.
assert(vm1.insertMoney(100) == ("Got a bottle!", 0))
assert(vm1.getBottleCount() == 99)
assert(vm1.stillOwe() == 125)
assert(str(vm1) == "Vending Machine:<99 bottles; $1.25 each; $0 paid>")
# If the user pays too much money, they get their change back with the
# bottle.
assert(vm1.insertMoney(500) == ("Got a bottle!", 375))
assert(vm1.getBottleCount() == 98)
assert(vm1.stillOwe() == 125)
# Machines can become empty
vm2 = VendingMachine(1, 120)
assert(str(vm2) == "Vending Machine:<1 bottle; $1.20 each; $0 paid>")
assert(vm2.isEmpty() == False)
assert(vm2.insertMoney(120) == ("Got a bottle!", 0))
assert(vm2.getBottleCount() == 0)
assert(vm2.isEmpty() == True)
# Once a machine is empty, it should not accept money until it is restocked.
assert(str(vm2) == "Vending Machine:<0 bottles; $1.20 each; $0 paid>")
assert(vm2.insertMoney(25) == ("Machine is empty", 25))
assert(vm2.insertMoney(120) == ("Machine is empty", 120))
assert(vm2.stillOwe() == 120)
vm2.stockMachine(20) # Does not return anything
assert(vm2.getBottleCount() == 20)
assert(vm2.isEmpty() == False)
assert(str(vm2) == "Vending Machine:<20 bottles; $1.20 each; $0 paid>")
assert(vm2.insertMoney(25) == ("Still owe $0.95", 0))
assert(vm2.stillOwe() == 95)
vm2.stockMachine(20)
assert(vm2.getBottleCount() == 40)
# We should be able to test machines for basic functionality
vm3 = VendingMachine(50, 100)
vm4 = VendingMachine(50, 100)
vm5 = VendingMachine(20, 100)
vm6 = VendingMachine(50, 200)
vm7 = "Vending Machine"
assert(vm3 == vm4)
assert(vm3 != vm5)
assert(vm3 != vm6)
assert(vm3 != vm7) # should not crash!
s = set()
assert(vm3 not in s)
s.add(vm4)
assert(vm3 in s)
s.remove(vm4)
assert(vm3 not in s)
assert(vm4.insertMoney(50) == ("Still owe $0.50", 0))
assert(vm3 != vm4)
print("Done!")
##############################################
# testAll and main
##############################################
def testAll():
testPowerSum()
testIsHappyNumber()
testEvalPrefixNotation()
testVendingMachineClass()
def main():
#cs112_f17_week9_linter.lint() # check style rules
testAll()
if __name__ == '__main__':
main()
|
aa58d5137d030325b36ca1cfe2657e9672bb6b7b | RWaiti/URI | /1146.py | 228 | 3.71875 | 4 | # -*- coding: utf-8 -*-
N = 1
while N != 0:
N = int(input())
if N != 0:
for i in range(N):
print (str(i+1),end="")
if i+1 != N:
print(' ',end="")
print() |
9e68055784aa55e5aa1ab50588d21fd16ede704c | Mumulhy/LeetCode | /面试题04.06-后继者/InorderSuccessor.py | 767 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# LeetCode 面试题04.06-后继者
"""
Created on Mon May 16 10:28 2022
@author: _Mumu
Environment: py38
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
ans = None
if p.right:
node = p.right
while node:
ans = node
node = node.left
return ans
node = root
while node is not p:
if node.val > p.val:
ans = node
node = node.left
else:
node = node.right
return ans
|
8a91c59d1fc909dca53cd0a05e3861c66040adce | lrj1197/Python | /Analytics/Bullshit_project.py | 5,949 | 3.671875 | 4 | '''
This Program allows one to input data in the form of
'source of bs # date gathered # type of bs(political, eduacational, social) # kind of bs(plots, tweet, etc)'
Then sift through the input and add the data to their lists. when finished enter 'end' to terminate the
program and then put the data into a pd.dataframe and pickle the file for later use.
'''
import matplotlib.pyplot as plt
#import the input algorithm
import sorting_alg
#import search_alg
import seaborn as sb
#gathter the inputs and add them into a list
#before each entry, clear the lists before running bullshit!!!!! nope
#call the bs func input algorithm
bullshit()
#check the lists to make sure things we input properly
#bs.clear()
#date.clear()
#typ.clear()
#kind.clear()
print(bs)
print(kind)
print(date)
print(typ)
#create the bs dataframe
Bullshit_dataset = pd.DataFrame({'Source of Bullshit' : bs, 'Date': date , 'type': typ, 'kind': kind})
#check the dataframe
Bullshit_dataset
#pickle the dataframe.
Bullshit_dataset.to_pickle('Bullshit_dataset_final.pkl')
#Bullshit_dataset.to_pickle('Bullshit_dataset_1.pkl')
#Bullshit_dataset.to_pickle('Bullshit_dataset_2.pkl')
#Bullshit_dataset.to_pickle('Bullshit_dataset_3.pkl')
#Bullshit_dataset.to_pickle('Bullshit_dataset_4.pkl')
#Bullshit_dataset.to_pickle('Bullshit_dataset_5.pkl')
#Bullshit_dataset.to_pickle('Bullshit_dataset_6.pkl')
#unpickle all the files
day0 = pd.read_pickle('Bullshit_dataset_2.pkl')
#day1 = pd.read_pickle('Bullshit_dataset_1.pkl')
#day2 = pd.read_pickle('Bullshit_dataset_2.pkl')
#day3 = pd.read_pickle('Bullshit_dataset_3.pkl')
#day4 = pd.read_pickle('Bullshit_dataset_4.pkl')
#day5 = pd.read_pickle('Bullshit_dataset_5.pkl')
#day6 = pd.read_pickle('Bullshit_dataset_6.pkl')
day0
#store all files in list
#files = [day0, day1, day2, day3, day4, day5, day6]
#merge all the dataframes into a master file
Bullshit_dataset_master = pd.concat([day0])
#repickle the master dataframe and create a master pickle
Bullshit_dataset_master.to_pickle('Bullshit_dataset_master.pkl')
'''
Now time for the analysis. Looking at the raw data, checking for negative times,
looking at grouping terms that are similar, ie (twitter, tweet, tweeted ... etc)
sort the data and group the sources, report which place spread the most bs
and of what form. Generate plots and models to help explain... NO BIAS
'''
bsm = pd.read_pickle('Bullshit_dataset_final.pkl')
#look at the raw dataset
bsm
#sort through the dates and discard any erroneous values.
#check for any outliers.
#the sorting_alg takes care of most of the cleaning of the data. This is more of
#safty net in case the sorting_alg missed something.
bsm['Day'] = bsm['Date'].dt.day
#generate hist of the dates
plt.figure(); bsm['Day'].hist(bins = 7,label = 'Bullshit for the Week'); plt.show()
'''
1) What day was i given the most bs?
2) What type of bs was given the most? And from what source?
3) look at where the bs came from. How much was from news outlets? from me? from books, class, and school? the internet?
'''
bsm['Source of Bullshit']
me = ['luke', 'lucas', 'me', 'Luke', 'Lucas', 'Me']
#finds the values that are from me and returns the percentage of the total that came from me.
bsm_me = bsm['Source of Bullshit'][np.isin(bsm['Source of Bullshit'], me) == True]
bsm_me.dropna()
#get the length of the bsm_me dataframe and the master and calc/show the percentage of bs that comes
#from me.
m = len(bsm_me); b = len(bsm); x = m/b*100
print('The amount of BS the comes from me is, %f percent' % x)
#finds the values that are not from me
bsm_nme = bsm['Source of Bullshit'][np.isin(bsm['Source of Bullshit'], me) == False]
bsm_nme.dropna()
bsm_profs = bsm['Source of Bullshit'][np.isin(bsm['Source of Bullshit'], 'germs prof') == True]
prof = len(bsm_profs)
#get the length of the bsm dataframe and the master and calc/show the percentage of bs that comes
#from my professors and other sources.
j = prof/b*100
k = 100 - (j+x)
print('The amount of BS the comes from my professors is, %f percent' % j)
print('The amount of BS the Comes from other sources is, %f percent' % k)
'''
As of 3/8/18 I only contribute 29.4 % of the BS in my life, granted that is mostly on purpose as an instructional tool for teaching
32.4 % comes from my professors. The BS is mostly in the form of statistics and plots generated by third parties. My professorsare not
generating BS, they are mearly distrubuting it. 38 % comes from other sources. This is mostly News outlets and news articles. Most of their
BS comes in the form of misquoting tweets or writing an article based on a tweet about a policy that was spoken about... a lot of places where
the full story could get lost.
'''
'''
Other questions to ask.
1) How much came from professors? from the News? Other sources?
2) Pie charts of the different datasets. Check
3) Look at the different types that came in and how many of the different types there are.
4)
'''
#gernerate a better lsit, or seperate the bsm[kind] to find if tweet or quote is in the name.
kd = ['quotes', 'tweets', 'tweet', 'Qoutes', 'Quote']
bsm['kind'][np.isin(bsm['kind'], kd) == True]
bsm['kind']
#faster way?
edu = bsm.type[np.isin(bsm.type, 'educational')]
e = len(edu)
polt = bsm.type[np.isin(bsm.type, 'political')]
pol = len(polt)
per = bsm.type[np.isin(bsm.type, 'personal')]
pe = len(per)
soc = bsm.type[np.isin(bsm.type, 'social')]
s = len(soc)
non = bsm.type[np.isin(bsm.type, '')]
n = len(non)
fracs = [pol,s,e,pe,n]
lables = ['political', 'social', 'educational', 'personal', 'None']
plt.figure();plt.pie(fracs, labels = lables, autopct='%.2f');plt.show()
bsm['edu'] = edu
f = []
for i in range(len(bsm)):
if bsm['me'][i] == np.nan:
if bsm['edu'][i] == np.nan:
np.nan
else:
f.append(i)
bsm['combo'] = pd.DataFrame({'combo': f})
bsm
#bsm['me'] = bsm_me
#plt.figure(); bsm['mw'].hist(bins = 7,label = 'Bullshit for the Week'); plt.show()
|
c3d6967017f9d43cb4b54d23533d2b747faaf2bc | jonathanrhyslow/mytrix | /mytrix/vector.py | 9,183 | 3.6875 | 4 | """Module for general matrix class."""
from random import randrange
from math import sqrt
import mytrix.exceptions as exc
import mytrix.matrix as mat
class Vector:
"""A class to represent a general matrix."""
def __init__(self, m, data):
"""Initalise vector dimensions and contents."""
self.m = m
self.data = data
def __eq__(self, vct):
"""Evaluate whether two vectors are equal."""
if not isinstance(vct, Vector):
return False
if not (self.m == vct.m):
return False
for i in range(self.m):
if self[i] != vct[i]:
return False
return True
def __add__(self, obj):
"""Add a valid object to this vector and return the result.
Doesn't modify the current vector. Valid objects include other vectors
and numeric scalars
"""
if isinstance(obj, Vector):
if self.m != obj.m:
raise exc.ComformabilityError(
"vectors must have the same length")
data = [self[i] + obj[i] for i in range(self.m)]
elif Vector.is_numeric(obj):
data = [self[i] + obj for i in range(self.m)]
else:
raise TypeError(
"cannot add object of type " + type(obj) + " to vector")
return Vector(self.m, data)
def __sub__(self, obj):
"""Subtract a valid object from this vector and return the result.
Doesn't modify the current vector. Valid objects include other vectors
and numeric scalars
"""
if isinstance(obj, Vector):
if self.m != obj.m:
raise exc.ComformabilityError(
"vectors must have the same length")
data = [self[i] - obj[i] for i in range(self.m)]
elif Vector.is_numeric(obj):
data = [self[i] - obj for i in range(self.m)]
else:
raise TypeError(
"cannot subtract object of type " + type(obj) +
" to vector")
return Vector(self.m, data)
def __mul__(self, obj):
"""Multiply this vector by a scalar.
Doesn't modify the current matrix.
"""
if Vector.is_numeric(obj):
data = [self[i] * obj for i in range(self.m)]
return Vector(self.m, data)
else:
raise TypeError(
"cannot add object of type " + type(obj) + " to matrix")
def __floordiv__(self, obj):
"""Divide this vector by a scalar.
Doesn't modify the current vector
"""
if Vector.is_numeric(obj):
data = [self[i] // obj for i in range(self.m)]
return Vector(self.m, data)
else:
raise TypeError(
"cannot add object of type " + type(obj) + " to matrix")
def __truediv__(self, obj):
"""Divide this vector by a scalar.
Doesn't modify the current vector
"""
if Vector.is_numeric(obj):
data = [self[i] / obj for i in range(self.m)]
return Vector(self.m, data)
else:
raise TypeError(
"cannot add object of type " + type(obj) + " to matrix")
def __pos__(self):
"""Unary positive. Included for symmetry only."""
data = [+self[i] for i in range(self.m)]
return Vector(self.m, data)
def __neg__(self):
"""Negate all elements of the vector."""
data = [-self[i] for i in range(self.m)]
return Vector(self.m, data)
def __iadd__(self, obj):
"""Add a vector to this vector, modifying it in the process."""
# calls __add__
tmp = self + obj
self.data = tmp.data
return self
def __isub__(self, obj):
"""Subtract a vector from this vector, modifying it in the process."""
# calls __sub__
tmp = self - obj
self.data = tmp.data
return self
def __imul__(self, obj):
"""Multiply this vector by a scalar, modifying it in the process."""
# calls __mul__
tmp = self * obj
self.data = tmp.data
return self
def __ifloordiv__(self, obj):
"""Divide this vector by a scalar, modifying it in the process."""
# calls __floordiv__
tmp = self // obj
self.data = tmp.data
return self
def __itruediv__(self, obj):
"""Divide this vector by a scalar, modifying it in the process."""
# calls __truediv__
tmp = self / obj
self.data = tmp.data
return self
def __radd__(self, obj):
"""Implement reflected addition."""
# calls __add__
return self + obj
def __rsub__(self, obj):
"""Implement reflected subtraction."""
# calls __sub__
return -self + obj
def __rmul__(self, obj):
"""Implement reflected multiplication."""
return self * obj
def __getitem__(self, key):
"""Get element in ith position."""
self.__check_key_validity(key)
return self.data[key]
def __setitem__(self, key, val):
"""Set element in ith position."""
self.__check_key_validity(key)
self.data[key] = val
def __check_key_validity(self, key):
"""Validate keys for __getitem__() and __setitem__() methods."""
if not isinstance(key, int):
raise TypeError("key must be an integer")
if not 0 <= key < self.m:
raise exc.OutOfBoundsError("key is out of bounds")
def project_onto(self, v):
"""Project this vector onto another."""
if not isinstance(v, Vector):
raise TypeError("can only project onto a vector")
if all([v[i] == 0 for i in range(v.m)]):
raise exc.LinearAlgebraError("cannot project onto a zero vector")
return (Vector.dot(self, v) / Vector.dot(v, v)) * v
def normalise(self):
"""Normalise this vector."""
return self / self.magnitude
@property
def magnitude(self):
"""Calculate the magnitude of this vector"""
return sqrt(Vector.dot(self, self))
@classmethod
def makeRandom(cls, m, min=0, max=1):
"""Create random vector.
Make a random vector of length m with elements chosen
independently and uniformly from the interval (min, max).
"""
Vector.validate_dimension(m)
data = [randrange(min, max) for i in range(m)]
return Vector(m, data)
@classmethod
def makeZero(cls, m):
"""Make a zero vector of dimension m."""
Vector.validate_dimension(m)
data = [0 for i in range(m)]
return Vector(m, data)
@classmethod
def makeOne(cls, m):
"""Make a vector of ones of dimension m."""
Vector.validate_dimension(m)
data = [1 for i in range(m)]
return Vector(m, data)
@classmethod
def fromList(cls, elems, **kwargs):
"""Make vector from list."""
m = kwargs.get('m')
num_elems = len(elems)
if m is None:
m = num_elems
elif m != num_elems:
raise ValueError("dimension does not match number of elements in"
"list")
data = [elems[i] for i in range(m)]
return Vector(m, data)
@classmethod
def fromMatrixColumn(cls, mtrx, col):
"""Extract a column of a matrix as a vector."""
if not isinstance(mtrx, mat.Matrix):
raise TypeError("can only extract a column from a matrix")
if not isinstance(col, int):
raise TypeError("col must be an integer")
if not 0 <= col < mtrx.n:
raise exc.OutOfBoundsError("column is out of bounds")
data = [mtrx[i, col] for i in range(mtrx.m)]
return Vector(mtrx.m, data)
@staticmethod
def validate_dimension(m):
"""Check whether a vector dimension is valid."""
if not isinstance(m, int):
raise TypeError("dimension must be integral")
if m <= 0:
raise ValueError("dimension must be positive")
@staticmethod
def is_numeric(obj):
"""Check if a given object is of a numeric type.
Note that since bool inherits from int, that this will accept
Boolean values
"""
return isinstance(obj, (int, float, complex))
@staticmethod
def dot(u, v):
"""Calculate the dot product of two vectors"""
if not (isinstance(u, Vector) and isinstance(v, Vector)):
raise TypeError("can only dot two vectors")
if u.m != v.m:
raise ValueError("vector lengths do not match")
return sum([e1 * e2 for e1, e2 in zip(u.data, v.data)])
@staticmethod
def hadamard(u, v):
"""Calculate the Hadamard product of two vectors"""
if not (isinstance(u, Vector) and isinstance(v, Vector)):
raise TypeError("can only Hadamard two vectors")
if not u.m != v.m:
raise ValueError("vector lengths do not match")
data = [e1 * e2 for e1, e2 in zip(u.data, v.data)]
return Vector(u.m, data)
|
753944fbe3f0d194450510aec6c740900c6db7f0 | Paper-SSheets/PositivityBot | /positive_sayings.py | 6,298 | 3.640625 | 4 | # Create a list and just append whatever you want to it!
positive_sayings = list()
positive_sayings.append("You are a unique child of this world.")
positive_sayings.append("You have as much brightness to offer the world as the next person.")
positive_sayings.append("You matter and what you have to this world also matters.")
positive_sayings.append("Trust yourself.")
positive_sayings.append("The situation you're in will work out for your highest good.")
positive_sayings.append("Wonderful things will unfold before you.")
positive_sayings.append("Draw from your inner strength and light.")
positive_sayings.append("You may not make all the right choices, but you'll grow from all of them.")
positive_sayings.append("Feel the love from those not physically around you.")
positive_sayings.append("You are too big a gift to this world to feel self-pity.")
positive_sayings.append("I love and approve of you.")
positive_sayings.append("Forgive yourself for all the mistakes you've made. They've made you better.")
positive_sayings.append("Let go of your anger so you can see things clearly.")
positive_sayings.append("Accept responsibility if your anger has hurt anyone, and work to rememedy it.")
positive_sayings.append("Replace your anger with understanding and compassion.")
positive_sayings.append("You may not understand the good in this situation, but it is there, time will tell.")
positive_sayings.append("Muster up more hope and courage from deep inside you.")
positive_sayings.append("Choose to find hopeful and optimistic ways to look at your situation.")
positive_sayings.append("It's ok to ask for help and guidance - it's not weakness, it's intelligence.")
positive_sayings.append("Refuse to give up, there's always another way.")
positive_sayings.append("Never stop loving.")
positive_sayings.append("Receive all feedback with kindness, but ultimately you make the final call.")
positive_sayings.append("Continue showing love to everyone, it will come back to you.")
positive_sayings.append("You are a better person from all the pain you've gone through.")
positive_sayings.append("Choose friends who approve and love you.")
positive_sayings.append("Surround yourself with people who treat you well.")
positive_sayings.append("Take the time to show your friends that you care about them.")
positive_sayings.append("Take great pleasure with your friends, even if you disagree or live different lives.")
positive_sayings.append("You play a huge role in your own career success.")
positive_sayings.append("What you do is meaningful and rewarding.")
positive_sayings.append("Believe in your ability to change the world with the work that you do.")
positive_sayings.append("Engage in activities that impact this world positively.")
positive_sayings.append("Peaceful sleep awaits for you in the dreamland.")
positive_sayings.append("Let go of all the false stories that you make up in your head.")
positive_sayings.append("Release your mind of throught until you wake up.")
positive_sayings.append("Embrace the peace and quiet of the night.")
positive_sayings.append("The day will bring you nothing but growth.")
positive_sayings.append("Today will be a gorgeous day to remember.")
positive_sayings.append("Your thoughts are your reality so think up a bright new day.")
positive_sayings.append("Fill up your day with hope and face it with joy.")
positive_sayings.append("Choose to fully participate in your day.")
positive_sayings.append("Let go of worries that simply drain your energy.")
positive_sayings.append("You are a smart, caluclated person.")
positive_sayings.append("You are in complete charge of planning for your future.")
positive_sayings.append("Trust in your own abilities.")
positive_sayings.append("Follow your dreams no matter what.")
positive_sayings.append("If they don't support you, don't associate with them.")
positive_sayings.append("Pursue your dream.")
positive_sayings.append("All your problems have a solution. Find it")
positive_sayings.append("You are safe and sound. All is well.")
positive_sayings.append("There is a great reason this is unfolding before me now.")
positive_sayings.append("You have the smarts and the ability to get through this.")
positive_sayings.append("Seek a new way of thinking about your situation.")
positive_sayings.append("The answer is right before you, even if you can't see it yet.")
positive_sayings.append("Believe in your ability to unlock the way and set yourself free.")
positive_sayings.append(
"You have no right to compare yourself to anyone, for you do not know their whole story, nor them, yours.")
positive_sayings.append("Compare youself only to that of your highest self.")
positive_sayings.append("Choose to see the light that you are to this world.")
positive_sayings.append("Be happy in your own skin and in your own circumstances.")
positive_sayings.append("You are a gift to everyone who interacts with you.")
positive_sayings.append("You are more than good enough and you're getting better every day.")
positive_sayings.append("Adopt the mindset to praise yourself.")
positive_sayings.append("Give up that self-critical habit.")
positive_sayings.append("See the perfection in all your flaws and all your genius.")
positive_sayings.append("You ARE a good person at all times of day and night.")
positive_sayings.append("Bad thoughts do not make you a bad person.")
positive_sayings.append("We all struggle, it's ok, you're strong. I believe in you.")
positive_sayings.append("You cannot give up until you have tried every single possible conceivable way.")
positive_sayings.append("Giving up is easy and always an option, so let's delay it for another day.")
positive_sayings.append("Press on, your path is true.")
positive_sayings.append("It is always too early to give up on your goals.")
positive_sayings.append("You've already traversed so far through the dark tunnel, don't give up just yet.")
positive_sayings.append("The past has no power over you anymore.")
positive_sayings.append("Embrace the rhythm ad the flowing of your own heart.")
positive_sayings.append("All that you need comes to you at the right time and place in this life.")
positive_sayings.append("You should be deeply fulfilled with who you are.")
|
afac4f7ef191d6912c7e22e424be4d1f75521099 | poojataksande9211/python_data | /python_tutorial/excercise/ip_char_count_full_string.py | 183 | 3.671875 | 4 | name=input("enter name")
temp_var =""
i=0
while i< len(name):
if name[i] not in temp_var:
temp_var += name[i]
print(f"{name[i]}:{name.count(name[i])}")
i += 1
|
6cdf8bd3910c26fa9da98dadf612eb4da4b90067 | arpit0891/Project-Euler | /problem_01/sol7.py | 536 | 4.25 | 4 | """
Problem Statement:
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3,5,6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.
"""
def solution(n):
"""Returns the sum of all the multiples of 3 or 5 below n.
"""
//Solution
result = 0
for i in range(n):
if i % 3 == 0:
result += i
elif i % 5 == 0:
result += i
return result
if __name__ == "__main__":
print(solution(int(input().strip())))
|
0ee606574fd3760b22f6c4220320aa6e0fcfb6f5 | Fenmaz/connect4 | /minimax/src/minimax_tentative_solver_fail.py | 6,879 | 3.515625 | 4 | '''
Aim is to create a solver that outputs how many steps are left
to end up with a win/lose/draw for the current player.
I am assuming that it's player 1's turn given the current
configuration of the board.
I referred to an example of the Negamax solver: http://blog.gamesolver.org/solving-connect-four/03-minmax/
I first read the data from connect-4.data and then organize them into grid form.
Similar to what the author in the above link did, I place 1 for player 1, 2 for player 2 and 0 for blank cells
Then using the scoring method described in the above link, I try to run the negamax algorithm.
'''
from classification.src import data_util
'''================== I/O Methods ====================='''
'''
If the cell in the board is blank, assign 0
If the cell in the board is taken by player 1, assign 1
If the cell in the board is taken by player 2, assign 2
'''
def assign(c):
if c == "b":
return 0
elif c == "x":
return 1
elif c == "o":
return 2
'''
Convert the given data string to a 6x7 board
Return the board and the win/loss/draw tag for the first player.
'''
def toBoard(pos):
# declare an nxm board
n = 6
m = 7
board = [[0]*m for i in range(n)]
pos = pos.split(',')
i = 0
col = 0
while i < len(pos)-1:
for j in range(6):
row = 5-j
board[row][col] = assign(pos[i+j])
i += 6
col += 1
return([board,pos[len(pos)-1]])
'''
Extract data line by line from the given connect-4.data
We return each of the 6x7 board configuration as well as
the win/loss/draw tag for the first player for each configuration
'''
def Positions(filepath):
data = []
with open(filepath) as fp:
for cnt,line in enumerate(fp):
line = line[:-1]
data.append(line)
fp.close()
ret = [] # array containing tuple: (6x7 board, win/loss/draw tag)
for pos in data:
ret.append(toBoard(pos))
return(ret)
'''================== Storing board information and solving ====================='''
'''
The Board class contains information about the given configuration of the board,
as well as whether the current player will win/lose or end up in a draw if he/she makes a
move on the given board. Also contains information about the dimension of the board.
'''
class Board:
def __init__(self,board,status,moves=0,row=6,col=7):
self.board = board
self.status = status
self.moves = moves
self.row = row
self.col = col
# we fill up the height information for each column
self.height = [0]*col
for i in range(self.col):
for j in range(self.row):
if self.board[self.row-j-1][i] != 0:
self.height[i] += 1
def Moves(self):
return(self.moves)
def canPlace(self,pos): #pos = which column number
return(self.height[pos] < self.row)
def Place(self,pos):
if self.height[pos] < 6:
self.board[self.height[pos]][pos] = 1+self.moves%2
self.height[pos] += 1
self.moves += 1
'''
Indicates if the player will win by placing
on the given column (pos). We can optimize using method used by Trung (bit configurations stored in hash map)
The current implementation is a bit messy
'''
def isWinningMove(self,pos):
current_player = 1+self.moves%2
# vertical check
if self.height[pos] >= 3 and self.board[self.height[pos]-1][pos] == current_player and self.board[self.height[pos]-2][pos] == current_player and self.board[self.height[pos]-1][pos] == current_player:
return True
# horizontal check in left direction
x = self.height[pos]
y = pos-1
cnt = 0
while y >= 0 and y < self.col and self.board[x][y] == current_player:
y -= 1
cnt += 1
if cnt == 3:
return True
# horizontal check in right direction
cnt = 0
y = pos+1
while y >= 0 and y < self.col and self.board[x][y] == current_player:
y += 1
cnt += 1
if cnt == 3:
return True
# diagonal NW direction
cnt = 0
x = self.height[pos]-1
y = pos-1
while x >= 0 and x < self.row and y >= 0 and y < self.col and self.board[x][y] == current_player:
x -= 1
y -= 1
cnt += 1
if cnt == 3:
return True
# diagonal NE direction
cnt = 0
x = self.height[pos]-1
y = pos+1
while x >= 0 and x < self.row and y >= 0 and y < self.col and self.board[x][y] == current_player:
x -= 1
y += 1
cnt += 1
if cnt == 3:
return True
# diagonal SW direction
cnt = 0
x = self.height[pos]+1
y = pos-1
while x >= 0 and x < self.row and y >= 0 and y < self.col and self.board[x][y] == current_player:
x += 1
y -= 1
cnt += 1
if cnt == 3:
return True
# diagonal SE direction
cnt = 0
x = self.height[pos]+1
y = pos+1
while x >= 0 and x < self.row and y >= 0 and y < self.col and self.board[x][y] == current_player:
x += 1
y += 1
cnt += 1
if cnt == 3:
return True
# if the checks all fail
return False
'''
Using scoring metric defined in
http://blog.gamesolver.org/solving-connect-four/02-test-protocol/
Once we obtain the score, we can also use this information to figure out the number of steps until the current player wins/loses/draws.
This implementation does not work because it exceeds maximum recursion depth.
Also it is extremely slow.
'''
def Negamax(board): # board is an instance of Board
if board.Moves() == board.row * board.col:
return 0
for pos in range(board.col):
if board.canPlace(pos) == True and board.isWinningMove(pos) == True:
return (board.row * board.col + 1 - board.Moves())/2
best = -board.row*board.col
for pos in range(board.col):
if board.canPlace(pos) == True:
Board2 = Board(board.board,board.status)
Board2.Place(pos)
score = -Negamax(Board2)
if score > best:
best = score
return best
''' printing out grid for debugging purposes '''
def printGrid(a):
for i in range(6):
for j in range(7):
print(a[i][j],end='')
print()
'''================== Main Function ====================='''
if __name__ == "__main__":
data_util.download() # download data if it is not already available
filepath = 'data/connect-4.data'
ret = Positions(filepath)
test = ret[0]
b = Board(test[0],test[1])
score = Negamax(b)
print(score)
|
a5c05491a9937db3090b9d4ecf45a11d04382bc2 | SandyHuang0305/python | /階乘練習.py | 529 | 3.96875 | 4 | # 階乘練習
#讓用戶輸入數字
num = int(input('請輸入一個數字:'))
factorial = 1
#確認該數是正負數
if num < 0:
print('負數沒有階乘的喔')
elif num == 0:
print('0的階乘為1')
else:
for i in range(1, num + 1):
factorial = factorial * i
print(num, '的階乘為', factorial)
#利用math庫
import math
num = int(input('請輸入一個數字:'))
if num < 0:
print('負數沒有階乘的喔')
else:
print(num, '的階乘為',math.factorial(num) )
|
71edf37aae002bf73035c2a3c18d47597d03f848 | crzysab/Learn-Python-for-Beginners | /010-Operators/Operator_Special.py | 375 | 4.15625 | 4 | #Membership operator
x = 'Hello World'
print("'H' in x : ", 'H' in x) #Return True
print("'S' in x : ", 'S' in x) #Return False
print("'T' not in x : ", 'T' not in x) #Return True
y = {1:'a', 2:'b'}
print("1 in y : ", 1 in y)
print("'a' in y : ", 'a' in y)
#Identity operator
a = 'Hello'
b = 'hello'
c = 234
d = 432
print("a is b : ", a is b)
print("c is d : ", c is not d) |
80e5e095c57135f5afcfe4e0ce19fd3cd3c05a2b | DemetrioCN/python_projects_DataFlair | /basic_email_slicer.py | 289 | 3.796875 | 4 |
print("\n")
print(10*"-", "Email Slicer", 10*"_")
print("\n")
email = input("Introduce your email: ").strip()
user_name = email[:email.index('@')]
domain = email[email.index('@')+1:]
output = f'Your usernam is {user_name} and your domain name is {domain}'
print(output)
print('\n')
|
b0dc68843e6f552ca05ccda14ad2939a278cc921 | moussadiak87/Python | /Calculette/calc_objet/calculatrice_logique.py | 588 | 3.5625 | 4 | class Calculatrice_logique():
def __init__(self):
self.valeur1 = 0
self.valeur2 = 0
self.operateur = ""
"""
prendre les valeur qu'on rentre et afficher memoriser'
chronologique
entrer une premiere valeur
entrer un operateur
entrer une deuxieme valeur
demander le resultat
exemple : 5 * 89 =
valeur1, valeur2, operateur, resultat
ecrire 'saisir une valeur '
lire valeur1
ecrire 'saisir un operateur'
lire operateur
ecrire 'saisir une 2nde valeur'
lire valeur2
ecrire valeur1 operateur valeur2 (sous entendu: le resultat de l'operation en question)
""" |
2932154adc80fe884c7e6236885e29d7da88a969 | Tak1za/Python-DSA | /anagram_check.py | 295 | 3.875 | 4 | def anagramCheck(s1, s2):
dict1 = {}
dict2 = {}
for i in s1:
dict1[i] = dict1.get(i, 0) + 1
for i in s2:
dict2[i] = dict2.get(i, 0) + 1
if dict1 == dict2:
print("Anagram!")
else:
print("Not an Anagram!")
anagramCheck("apple", "elppa")
|
e213c0827982768b418fcf20fe20b738aa2e7510 | Mr0grog/example-numpy-attribute-property-issues | /example_module/__init__.py | 719 | 3.765625 | 4 | class ExampleClass:
"""
This is an example of how attributes and attributes that are properties get
formatted by numpydoc.
Attributes
----------
normal_attribute : str
This is a normal attribute, fully specified in class docstring.
property_attribute
"""
def __init__(self):
self.normal_attribute = 'hello'
@property
def property_attribute(self):
"""
This attribute is actually a property (i.e. it's actually a function
call under the hood). The description is pulled from the docstring of
the method that implements it.
Returns
-------
int
"""
return len(self.normal_attribute)
|
2aa46b0207d58dfd08fd26bb648cc4480a3a0cec | lntr0wert/python | /lab5-4.py | 448 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import math
a, b, c = input('Kvadratne rivnyanna vyglyady ax^2 + bx + c = 0 \n\n enter A, B, C :').split(' ')
a1 = int(a)
b1 = int(b)
c1 = int(c)
def descr():
descr_value = sqrt((b*b) - 4*a*c)
return descr_value
def x1():
x1_value = (-b + descr_value)/2*a
return x1_value
def x1():
x1_value = (-b - descr_value)/2*a
return x2_value
print('koreni rivnyanna is: ' + x1_value + ' ' + x2_value)
|
14f350ce3f11f0a86f4f14400c81cee735331178 | coultat/yieldlove | /picanha/dictionary2.py | 1,212 | 3.703125 | 4 | import random
from random import randint
class darcarta():
def __init__(self):
self.cartas = {'corazones':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'], 'diamantes':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'], 'picas':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'], 'treboles':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K']}
def primeravez(self):
naipe = random.choice(list(self.cartas))
carta = randint(0, len(self.cartas[naipe]) - 1)
return self.cartas[naipe][carta], naipe
def pillarcartas(self):
x = self.cartas
cartasdadas = []
y = 0
cartasdadas.append(x.primeravez)
return cartasdadas
'''
x = darcarta()
cartasdadas = []
y = 0
cartasdadas.append(x.primeravez())
while y < 53:
carta = x.primeravez()
z = 0
while z < y:
if carta == cartasdadas[z]:
y = y - 1
elif z == y - 1:
cartasdadas.append(carta)
z = z + 1
y = y + 1
return cartasdadas
'''
z = darcarta()
print(z.pillarcartas())
|
8bbe6935b1b439e16df05b8bf73bbf0c9b29b54f | antongiannis/phd_tools | /phdTools/graphs.py | 1,424 | 3.5625 | 4 | import matplotlib.pyplot as plt
def donut_chart(labels, sizes, explosion=True, colors=None):
"""
Creates a donut chart with explosion if selected.
Parameters
----------
labels: ndarray
An array with the labels for the donut chart.
sizes: ndarray
An array with the counts for each category for the donut chart.
explosion: bool, optional
Whether or not to explode the chart.
colors: list, optional
A palette of HEX colours to be used. An example is ['#5e3c99', '#e66101', '#fdb863', '#b2abd2']
Returns
-------
Axes of the plot.
"""
# Number of categories
n_categ = len(labels)
# explosion
explosion_size = 0.05 * explosion
explode = (explosion_size,) * n_categ
fig, ax = plt.subplots()
patches, texts, autotexts = plt.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', startangle=90,
pctdistance=0.85, explode=explode)
# draw circle
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
# Set colour to white inside
for autotext in autotexts:
autotext.set_color('white')
# Change font size
for text in texts:
text.set_fontsize(10)
# Equal aspect ratio ensures that pie is drawn as a circle
ax.axis('equal')
plt.tight_layout()
return fig, ax
|
3adb0122c6c2190389ffa9c91e2e3013f08310fa | alvinwang922/Data-Structures-and-Algorithms | /Trees/Tree-To-LinkedList.py | 1,529 | 4.21875 | 4 | """
Convert a Binary Search Tree to a sorted Circular Doubly-Linked List
in place. You can think of the left and right pointers as synonymous
to the predecessor and successor pointers in a doubly-linked list.
For a circular doubly linked list, the predecessor of the first element
is the last element, and the successor of the last element is the first
element. We want to do the transformation in place. After the
transformation, the left pointer of the tree node should point to its
predecessor, and the right pointer should point to its successor. You
should return the pointer to the smallest element of the linked list.
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def treeToDoublyList(self, root: 'Node'):
if not root:
return
dummy = Node(0, None, None)
prev = dummy
stack, node = [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
node.left, prev.right, prev = prev, node, node
node = node.right
dummy.right.left, prev.right = prev, dummy.right
return dummy.right
print(treeToDoublyList([]))
print(treeToDoublyList([4, 2, 5, 1, 3]))
print(treeToDoublyList([2, 1, 3]))
print("The linked lists above should be [], [1, 2, 3, 4, 5], \
and [1, 2, 3].")
|
636179e1a741fb3ec0dc7f3f0187d16cd0e9ab5d | srishtigyawali/Quiz-game-python | /quiz slack.py | 1,999 | 3.90625 | 4 | Question = ["Which one is the first search engine in internet?","Number of bits used in IPV6 address","Which one is the web browser invented in 1990",
"Which of the programming language is used to create program like applets?","What is the name of the first computer virus",
"Why do we use firewall ?","What are the numbers of layers in OSI model ? ",".gif is an extension of",
"Where is the headquareter of Microsoft office located in Washington ?"]
options = [['GOOGLE','ARCHIE','ALTAVISTA','WAIS'],['32 BIT','64 BIT','128 BIT','256 BIT'],['INTERNET EXPLORER','MOSAIC','MOZIALLA','NEXUS'],
['COBOL','C LANGUAGE','JAVA','BASIC'],['RABBIT','CREEPER VIRUS','ELK CLONER','SCA VIRUS'],['SECURITY','DATA TRANSMISSION','AUTHENTICATION','MONITORING'],['3','9','7','11'],
['IMAGE FILE','VIDEO FILE','AUDIO FILE','WORD FILE'],['TEXAS','NEW YORK','CALIFORNIA','WASHINGTON']]
Answer = ['ALTAVISTA','128 BIT','NEXUS','JAVA','CREEPER VIRUS','PROLOG','SECURITY','7 LAYERS','IMAGE FILE','WASHINGTON']
score = 0
doneQuestin = []
def enterQN():
global choice
global score
choice = int(input("Enter your question number from 1-9:"))
if choice not in doneQuestin:
print(Question[choice - 1])
print('The options are given below:')
print(options[choice - 1])
userAnswer = input("Enter your answer:").upper()
if(userAnswer == Answer[choice-1]):
print("Your answer is correct")
score = score + 1
else:
print("your answer is incorrect")
print("The correct answer is ", Answer[choice - 1])
doneQuestin.append(choice)
else:
print("Question is already done enter another question number")
enterQN()
print("Today! we are going to play interesting quiz game")
doneQuestion = []
for i in range(11):
enterQN()
print(score)
|
dc6954b2f8a2b214b28b9df6e6457865392caacb | htingwang/HandsOnAlgoDS | /LeetCode/0148.Sort-List/Sort-List.py | 916 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: return head
slow, fast, last = head, head, head
while fast and fast.next:
last = slow
slow = slow.next
fast = fast.next.next
last.next = None
#print("#", head, slow)
return self.merge(self.sortList(head), self.sortList(slow))
def merge(self, l1, l2):
if not l1: return l2
if not l2: return l1
#print(l1.val, l2.val)
if l1.val < l2.val:
l1.next = self.merge(l1.next, l2)
return l1
else:
l2.next = self.merge(l1, l2.next)
return l2
|
778643f545c86617fdc7094a9f6634e4c9ebd125 | MaxPower9090/micro_drip_2018 | /drip_time.py | 1,938 | 3.828125 | 4 | #!/usr/bin/python
# calculates from the yyyymmdd.txt the average temperature and returns a time in seconds calculated by some logic
import sys
import time
def drip_time():
# values are in a file yyyymmdd.txt
filename = time.strftime("%Y%m%d.txt") #generates the filename by the date
filename = "/home/pi/Temp/"+filename # .... yes....
messungen = 0 #values measured a day
summe =0 # sum of the values
av_temp = 0 # average temperature
std_drip = 3*60 # Stadard time for dayli watering- minimal
extra_drip = 0 # additional time
extra_einheit = 60 # ammount of time for increasing
drip_time = 0
try:
d = open(filename,"r")
except:
print ("oeffnen nicht moeglich")
sys.exit(0)
allezeilen = d.readlines() # saving the values in "allezeilen"
d.close()
for zeile in allezeilen: # read "allezeilen"
#print (zeile)
summe += float(zeile)
messungen +=1 # count the ammount of measurements
#print('\n')
#print ("Summe:", summe)
#print("Anzahl der Messungen: ", messungen)
#print"Anzahl der Messungen: ", messungen
av_temp = summe / messungen # calculating the average temperture
#print ("Durchschnittstemperatur:", av_temp)
#print('\n')
#print ("Durchschnittstemperatur: {0:1f}".format(av_temp))
#print "Durchschnittstemperatur: {0:1f}" .format(av_temp)
#auswertung der Durchschnittstemperatur und Errechnung der "drip_time"
if av_temp <= 20:
extra_drip = 0
elif av_temp<= 25:
extra_drip = 2*extra_einheit
elif av_temp<= 27:
extra_drip = 3*extra_einheit
elif av_temp<= 30:
extra_drip = 4*extra_einheit
else:
extra_drip = 6*extra_einheit
drip_time = std_drip + extra_drip # calculate the drip time "drip_time"
#print("Bewaesserungszeit in Minuten: ", drip_time/60)
#print "Bewaesserungszeit in Minuten: " , drip_time/60
return (drip_time)
sys.exit(0)
|
cdf3e7c5d17089a74430146bae2d9e114e4cfebe | sreejithr/SoundEx-Plus-Algorithm | /soundex_plus/soundex_plus.py | 3,396 | 3.578125 | 4 | chars = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z"]
H_GROUP = "7"
Y_GROUP = "8"
VOWEL_GROUP = "0"
# Letter classes
codes = [VOWEL_GROUP, "1", "2", "3", VOWEL_GROUP, "1", "2", H_GROUP, VOWEL_GROUP,
"2", "2", "4","5", "5", VOWEL_GROUP, "1", "2", "6", "2", "3", VOWEL_GROUP,
"1", H_GROUP, "2", Y_GROUP, "2"]
# Vowels are divided into further groups based on their sound
vowel_1 = '#'
vowel_2 = '$'
vowel_3 = '%'
vowel_4 = '*'
vowel_5 = '^'
# Vowel classification
classification = {
'A': vowel_1, 'AA': vowel_1, 'E': vowel_1, 'AI': vowel_1,
'EE': vowel_2, 'I': vowel_2, 'Y': vowel_2,
'U': vowel_3, 'OO': vowel_3, 'OU': vowel_3, 'AU': vowel_3,
'O': vowel_4
}
VOWEL_TRUNCATION = 2
class ImprovedSoundex(object):
"""
Improved Soundex is a heavily tricked out version of the traditional
Soundex algorithm where vowels are also classified according to their
sound.
It also has custom rules for 2 groups known as Y_GROUP and H_GROUP which
are ['Y'] and ['H', 'W'] respectively.
"""
def _get_vowel_code(self, text):
sequence = []
code = classification.get(text, None)
if code:
return code
prev = None
for letter in text:
if len(sequence) > 2:
break
if letter == prev:
continue
code = classification.get(letter, None)
if code:
sequence.append(code)
prev = letter
return ''.join(sequence) if sequence else None
def soundex_code(self, text):
code_sequence = []
vowels = []
for letter in text.upper():
try:
code = codes[chars.index(letter)]
except ValueError:
continue
if code == Y_GROUP:
# Consider 'Y' as vowel if previous is consonant
if not vowels:
code = VOWEL_GROUP
if code == VOWEL_GROUP:
vowels.append(letter)
continue
if code == H_GROUP:
# Add 'H' to code_sequence if previous is a vowel
if not vowels:
continue
if vowels:
# Truncate vowels to length of VOWEL_TRUNCATION
vowel_string = ''.join(vowels[:VOWEL_TRUNCATION])
code_sequence.append(self._get_vowel_code(vowel_string))
vowels = []
code_sequence.append(code)
# Handle the vowels at the end of the word
if vowels:
# Truncate vowels to length of VOWEL_TRUNCATION
vowel_string = ''.join(vowels[:VOWEL_TRUNCATION])
code_sequence.append(self._get_vowel_code(vowel_string))
# Remove all 'H's in the end
while code_sequence[-1] == H_GROUP:
code_sequence = code_sequence[:-1]
code_string = ''
prev = ''
# Convert the code_sequence `list` to a string
for char in code_sequence:
if char == prev or char is None:
continue
code_string += char
prev = char
return code_string
def compare(self, ying, yang):
return self.soundex_code(ying) == self.soundex_code(yang)
|
fe3c702df7f8d3d54b47e8ce578ba281e37e9bf2 | udwivedi394/binaryTree | /checkLargestBST.py | 2,563 | 3.953125 | 4 | class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
#Time complexity: O(n)
#This function returns the [MaxHeight,BSTstatusofCurrentNode,minimum of subtree,maximum of subtree]
def findLargestBSTUtil(root):
if root==None:
return [0,False,None,None]
#If current node is leaf node, count is 1, it is a BST, max and min is the data iteself
if root.left == None and root.right == None:
return [1,True,root.data,root.data]
#Initialize the leftCheck and RightCheck of the tree
leftCheck = [0,True,root.data,root.data]
rightCheck = [0,True,root.data,root.data]
#If left subtree is present
if root.left:
#Check if the immediate data of left subtree satisfies the BST condition
if root.left.data < root.data:
leftCheck = findLargestBSTUtil(root.left)
else:
#Otherwise Set the status as False
leftCheck = [0,False,None,None]
#Same as left Subtree
if root.right:
if root.right.data > root.data:
rightCheck = findLargestBSTUtil(root.right)
else:
rightCheck = [0,False,None,None]
print "I'm Node:",root.data,leftCheck,rightCheck
#If status of both the left and right subtree is BST, then
if leftCheck[1] and rightCheck[1]:
#Check if max of leftsubtree is less and min of rightsubtree is greater than current Node data
if leftCheck[3] <= root.data and rightCheck[2] >= root.data:
#Return the sum of nodes of left and right subtree + 1, status is BST, mini is the minimum from leftsubtree
#Max is the maximum from rightsubtree
return [leftCheck[0]+rightCheck[0]+1,True,leftCheck[2],rightCheck[3]]
#If any of above condition fails, then from here the BST status is false,
#And the tree which has max number of nodes will be returned
leftCheck[1] = rightCheck[1] = False
return leftCheck if leftCheck[0] > rightCheck[0] else rightCheck
def findLargestBST(root):
return findLargestBSTUtil(root)[0]
root = Node(5)
root.left = Node(2)
root.left.left = Node(1)
root.left.right = Node(3)
root.right = Node(4)
root1 = Node(50)
root1.left = Node(30)
root1.left.left = Node(5)
root1.left.right = Node(20)
root1.right = Node(60)
root1.right.left = Node(45)
root1.right.right = Node(70)
root1.right.right.left = Node(65)
root1.right.right.right = Node(80)
root1 = Node(50)
root1.left = Node(10)
root1.left.left = Node(5)
root1.left.right = Node(20)
root1.right = Node(60)
root1.right.left = Node(55)
root1.right.right = Node(70)
root1.right.left.left = Node(45)
root1.right.right.left = Node(65)
root1.right.right.right = Node(80)
maxBST = findLargestBST(root)
print maxBST
|
6b70a36ccbae97df8d76efaf19ba4e58d8926f24 | case/PyDomainr | /pydomainr/PyDomainr.py | 3,252 | 3.53125 | 4 | import requests
class PyDomainr(object):
def __init__(self, domain):
"""
Prepare the API urls
"""
self.DOMAIN = domain
self.SEARCH = "https://domai.nr/api/json/search?q=" + self.DOMAIN
self.INFO = "https://domai.nr/api/json/info?q=" + self.DOMAIN
def _api_search(self):
"""
Private method
Store the response from the search endpoint in json_response
"""
self.response = requests.get(self.SEARCH)
self.json_response = self.response.json()
return self.json_response
def _api_info(self):
"""
Private method
Store the response from the info endpoint in the json_response variable
"""
self.response = requests.get(self.INFO)
self.json_response = self.response.json()
return self.json_response
@property
def is_available(self):
"""
Returns a booleon statement about the availability of domain
"""
self.json_response = self._api_search()
self.available = self.json_response['results'][0]['availability']
if self.available == 'taken':
return False
elif self.available == 'available':
return True
else:
#Other return types are tld or maybe
return self.available
def available_domains(self):
"""
This method goes through the 6 domains and checks for the availability
and returns a list
"""
self.domains = []
self.json_response = self._api_search()
self.result = self.json_response['results']
i = 0
while i < 6:
if self.result[i]['availability'] == 'available':
self.domains.append(self.result[i]['domain'])
i += 1
return self.domains
def taken_domains(self):
"""
This method goes through the 6 domains and checks for the domains that
are not available and returns a list
"""
self.domains = []
self.json_response = self._api_search()
self.result = self.json_response['results']
i = 0
while i < 6:
if self.result[i]['availability'] != 'available':
self.domains.append(self.result[i]['domain'])
i += 1
return self.domains
@property
def whois_url(self):
"""
Return the Whois URL of the domain
"""
return self._api_info()['whois_url']
@property
def registrar(self):
return self._api_info()['registrars'][0]['registrar']
@property
def registrar_name(self):
return self._api_info()['registrars'][0]['name']
@property
def register_url(self):
return self._api_info()['registrars'][0]['register_url']
@property
def iana_url(self):
return self._api_info()['tld']['iana_url']
@property
def domain_idna(self):
return self._api_info()['tld']['domain_idna']
@property
def subdomain(self):
return self._api_info()['subdomain']
@property
def domain(self):
return self._api_info()['domain']
@property
def www_url(self):
return self._api_info()['www_url']
|
2f9a31bd41541d21d47b298e9f57ec4bec4c6823 | maximiliense/Data-science-2.0 | /engine/flags/flags.py | 2,357 | 3.71875 | 4 | import warnings
def deprecated(comment=''):
comment = '' if comment == '' else ' (' + comment + ')'
def _deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
def new_func(*args, **kwargs):
what = 'function' if type(func) is not type else 'class'
warnings.warn(
'Call to deprecated %s %s%s.' % (what, func.__name__, comment), category=DeprecationWarning
)
return func(*args, **kwargs)
set_func_attributes(new_func, func)
return new_func
return _deprecated
def duplicated(func):
def wrapper(*args, **kwargs):
warnings.warn('Code is duplicated.', category=DeprecationWarning)
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
wrapper.__dict__.update(func.__dict__)
return wrapper
def incorrect_structure(details):
def _incorrect_structure(func):
def new_func(*args, **kwargs):
warnings.warn('Incorrect code structure for %s: %s.' % (func.__name__, details), category=Warning)
return func(*args, **kwargs)
set_func_attributes(new_func, func)
return new_func
return _incorrect_structure
def gpu_cpu(details=''):
details = '' if details == '' else ' (' + details + ')'
def _gpu_cpu(func):
def new_func(*args, **kwargs):
warnings.warn('Incorrect GPU/CPU support for %s%s.' % (func.__name__, details), category=Warning)
return func(*args, **kwargs)
set_func_attributes(new_func, func)
return new_func
return _gpu_cpu
def incorrect_io(explanation=''):
explanation = '' if explanation == '' else ' (' + explanation + ')'
def _incorrect_io(func):
def new_func(*args, **kwargs):
warnings.warn('Incorrect IO support for %s%s.' % (func.__name__, explanation), category=Warning)
return func(*args, **kwargs)
set_func_attributes(new_func, func)
return new_func
return _incorrect_io
def set_func_attributes(new_func, old_func):
new_func.__name__ = old_func.__name__
new_func.__doc__ = old_func.__doc__
new_func.__dict__.update(old_func.__dict__)
|
dc987bb71704d72569af3cb87ae82f7d6669fb01 | mengqi0315/predict_car_sales_price | /workspace_for_python/Day04/1.类的创建.py | 1,103 | 4.3125 | 4 | # python中类的创建
# python中如何定义类中的方法 def 方法名(self,形参)
# 对象的创建语法:对象=类名()
# 对象的使用通过“.”
class Person:
def __init__(self,name,age):
"""
构造方法(创建对象,初始化对象)
self是指当前类对象
"""
self.name = name
self.age = age
print("我是人类的构造方法")
def introduce(self):
print("我叫{},我今年{}岁".format(self.name,self.age))
def __str__(self):
print("姓名:{},年龄:{}岁".format(self.name, self.age))
# 1.对象的创建使用Person()
admin = Person('admin',18) # p是通过类中的构造方法创建出的人对象
# 2.'admin',18是实参(实际存在的参数)
zhangsan = Person('张三',45)
# 3.对象的调用用.读作的,成员访问符
# print(admin.name,admin.age) # 对象.属性
#
#
# admin.introduce() # 对象.方法
print(admin) # 打印对象时会默认调用类中的__str__()方法,把对象的地址转换成所有属性的字符串
|
b4d4e8a27981ac596d7ac1e7edcce68f0bac5554 | jdobner/grok-code | /grid_challenge.py | 521 | 3.703125 | 4 | #!/bin/python3
# Complete the gridChallenge function below.
from typing import List
def gridChallenge(grid : List[str]):
'''
>>> gridChallenge(['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv'])
'YES'
>>> gridChallenge(['ebacd', 'aaaaa', 'olmkn', 'trpqs', 'xywuv'])
'NO'
'''
m = map(sorted, grid)
prev = None
for curr in m:
if prev:
for i in range(len(prev)):
if curr[i] < prev[i]:
return "NO"
prev = curr
return "YES"
|
c6cab78138c9cd7db3694b87b479ac97f87e1f35 | Bashorun97/python-trainings | /grade rewritten.py | 511 | 4.3125 | 4 | print('Enter a value between 0.0 an 1.0 to determine the corresponding grade')
score = float(input('Enter score: '))
msg = ''
def computegrade(score):
if score >= 0.90 and score <=1.00:
msg = 'A'
elif score >= 0.80 and score <=0.89:
msg = 'B'
elif score >= 0.70 and score <= 0.79:
msg = 'C'
elif score >= 0.60 and score <= 0.69:
msg = 'D'
elif score <= 0.59:
msg = 'F'
else:
msg = 'Bad score'
print(msg)
computegrade(score)
|
d7b3fc26d5dd4bf236d1e8d2bd56ca8f2fdb662e | q737645224/python3 | /python基础/python笔记/day07/exercise/charator_count.py | 638 | 3.640625 | 4 | # 练习:
# 输入一段字符串,打印出这个字符串中出现过的字符的出现次数
# 如:
# 输入:
# abcdabcaba
# 打印:
# a: 4次
# b: 3次
# d: 1次
# c: 2次
# 注:
# 不要求打印的顺序
s = input("请输入: ") # abcdabcaba
# 创建一个字典用来保存字符的个数
d = {}
for ch in s:
# 先判断这个字符以前是否出现过
if ch not in d: # 第一次出现
d[ch] = 1 # 将次数设置为1
else: # 不是第一次出现
d[ch] += 1
# 打印字符和出现过的次数
for k in d:
print(k, ':', d[k], '次')
|
88d8af1299c1aa9664a7ec20dddea6a766ff3b94 | DanielJmz12/Evidenicas-Programacion-avanzada | /Evidencia50_lista_alturas.py | 531 | 3.8125 | 4 | alturas = []
suma=0
mayor = 0
menor = 0
for x in range(5):
valor = float(input("ingresa una altura: "))
alturas.append(valor)
suma = suma+valor
promedio = suma/5
print("el promedio de alturas es: ")
print(promedio)
for x in range(5):
if alturas[x]>promedio:
mayor = mayor+1
else:
if alturas[x]<promedio:
menor=menor+1
print("personas mas altas al promedio: ")
print(mayor)
print("personas mas bajas al promedio: ")
print(menor)
|
ac7c4ba6c2458b2c9f4546aa575bddf8a1b1dcde | LiBReShiNn/algorithm-practice | /python/training/factorial.py | 250 | 4.1875 | 4 | def factorial(num):
if num == 1:
return 1
return num * factorial(num - 1)
def factorial_tail(acc, num):
if num == 1:
return acc
return factorial_tail(acc * num, num-1)
print(factorial(3))
print(factorial_tail(1, 3))
|
cda32d38509f0465e8fdf9b685c74ee2b3d462e1 | BrenoSDev/PythonStart | /Introdução a Programação com Python/Listas22.py | 615 | 3.9375 | 4 | #Pilha de Pratos
prato = 5
pilha = list(range(1, prato+1))
while True:
print('\nExistem %d pratos na pilha'%len(pilha))
print('Pilha atual:', pilha)
print('Digite E para empilhar um novo prato,')
print('ou D para desempilhar. S para sair.')
operação = input('Operação (E, D ou S): ')
if operação == 'D':
if len(pilha)>0:
lavado = pilha.pop(-1)
print('Prato %d lavado'%lavado)
else:
print('Pilha vazia! Nada para lavar.')
elif operação == 'E':
prato += 1 #Novo prato
pilha.append(prato)
elif operação == 'S':
break
else:
print('Operação inválida! Digite apenas E, D ou S!') |
2ac9ce33f37401cb2ae967f3d1040aaf61ae15a3 | himol7/Sosio-Submission | /Python/python5.py | 275 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 23:24:32 2018
Default Arguments
@author: Himol Shah
"""
def print_from_stream(n, stream=None):
if stream is None:
stream = EvenStream()
for _ in range(n):
print(stream.get_next())
|
a2b77513f2ed5b72ac1b6b472ae61a3b675feedb | Aasthaengg/IBMdataset | /Python_codes/p02420/s443234117.py | 287 | 3.546875 | 4 |
ans = []
while (1) :
word = input().strip()
try :
inputLen = int( input().strip() )
except :
break
for i in range(0, inputLen) :
h = int( input().strip() )
word = word[h:] + word[:h]
ans.append(word)
for s in ans :
print(s)
|
12660f04d11f30d60b93eef79be229799d039005 | olgaBovyka/BasicLanguagePython | /Урок 1/task6.py | 1,134 | 3.6875 | 4 | first_day_int = 0
total_int = 0
counter_int = 2
var_input = input("В первый день результат спортсмена составил a километров: ")
var_input2 = input("Суммарный результат пробежек не менее b километров: ")
if var_input.isdigit() and var_input2.isdigit():
first_day_int = int(var_input)
total_int = int(var_input2)
if first_day_int < total_int:
print("1-й день: %d" % (first_day_int))
while first_day_int < total_int:
print("%d-й день: %0.2f" % (counter_int, first_day_int + first_day_int * 0.1))
first_day_int = first_day_int + first_day_int * 0.1
counter_int += 1
print("Ответ: на %d-й день спортсмен достиг результата — не менее %d км." % (counter_int - 1, total_int))
else:
print("Спортсмен достиг результата в первый день.")
else:
print("Нужно вводить целые числа. Мы работаем с ними. Все остальное мимо. ") |
d8b6315ddf19b537ef1d43bdc296ab36f1199140 | pttran3141/python_practice | /canSum_DP.py | 1,600 | 3.5625 | 4 | ##############################################
#This solution will not work because of memo
# def canSum(targetSum, numbers, memo = None):
# if memo is None: memo = {}
# if (targetSum in memo):
# return memo[targetSum]
# if (targetSum == 0):
# return True
# if (targetSum < 0):
# return False
# for num in numbers:
# remainder = targetSum - num
# if (canSum(remainder, numbers,memo)==True):
# memo[targetSum] = True
# return True
# memo[targetSum] = False
# return False, memo
# print(canSum(7,[2,3])) # True
# print(canSum(7,[5,3,4,7])) # True
# print(canSum(7,[2,4])) # False
# print(canSum(8,[2,3,5])) # True
# print(canSum(300,[7,14])) # False
###########################################
# def canSum(targetsum, numbers):
# memo = dict()
# def canSum_helper(targetsum, numbers):
# # check in memory
# if targetsum in memo:
# return memo[targetsum]
# if targetsum < 0:
# return False
# if targetsum == 0:
# return True
# for number in numbers:
# remainder = targetsum - number
# if canSum_helper(remainder, numbers) == True:
# memo[targetsum] = True
# return True
# memo[targetsum] = False
# return False
# result = canSum_helper(targetsum, numbers)
# return result
# print(canSum(7,[2,3]))
# print(canSum(7,[5,3,4,7]))
# print(canSum(7,[2,4]))
# print(canSum(8,[2,3,5]))
# print(canSum(300,[7,14]))
|
b8e9c82569c7beaa0a943fa22d4332c8e1fa913e | zhangke8/Applications | /Python/ceiling floor.py | 4,718 | 4.21875 | 4 | #####################################################################
# Author: Kevin Zhang
# Date: 12/20/2014
# purpose: calculate ceiling and floor values
#####################################################################
def ceiling(c):
########################################
# purpose: does ceiling operations
########################################
if (int(float(c)) > 0) == True:
return (int(float(c)) + 1)
else:
return (int(float(c)))
def floor(f):
#####################################
# purpose: does floor operations
#####################################
if (int(float(f)) > 0) == True:
return (int(float(f)))
else:
return (int(float(f)) - 1)
def main():
print("""
MENU
ceiling: c
floor: f
quit: q
""")
print("--------------------------------------------------------------------------------")
response = input("What would you like to do?: ")
while (True):
if response.lower()== "q":
print("Thanks for Playing!")
quit()
elif response.lower() == "c":
compute = input("Enter value to take ceiling of: ")
print("""
MENU
-------------------------------------------------------------
addition: add
subtraction: sub
NOTES: only add 1 space between addition or subtraction signs
""")
question = input("Would you like to add or subtract a number?: (Y/N) ")
if question.lower() == "y":
menu_select = input("Please select an option from the above menu: ")
if menu_select.lower() == "add":
find = compute.find("+")
ceiling_operation = float(compute[:find])
arithmetic = float(compute[find+2:])
print("The ceiling of ",ceiling_operation," + ",arithmetic,"is ", ceiling(ceiling_operation) + arithmetic)
elif menu_select.lower() == "sub":
find = compute.find("-")
find1 = compute[find+1:].find("-")
ceiling_operation = float(compute[:find1])
arithmetic = float(compute[find1+2:])
print("The ceiling of ",ceiling_operation," - ",arithmetic,"is ", ceiling(ceiling_operation) - arithmetic)
elif question.lower() == "n":
print("The ceiling of ",compute,"is ", ceiling(compute))
else:
print("Unknown response, please try again")
question = input("Would you like to add or subtract a number?: (Y/N) ")
response = input("What would you like to do?: ")
elif response.lower() == "f":
compute = input("Enter value to take ceiling of: ")
print("""
MENU
addition: add
subtraction: sub
NOTES: only add 1 space between addition or subtraction signs
""")
question = input("Would you like to add or subtract a number?: (Y/N) ")
if question.lower() == "y":
menu_select = input("Please select an option from the above menu: ")
if menu_select.lower() == "add":
find = compute.find("+")
floor_operation = float(compute[:find])
arithmetic = float(compute[find+2:])
print("The floor of ",floor_operation," + ",arithmetic,"is ", floor(floor_operation) + arithmetic)
elif menu_select.lower() == "sub":
find = compute.find("-")
find1 = compute[find+1:].find("-")
floor_operation = float(compute[:find1])
arithmetic = float(compute[find1+2:])
print("The floor of ",floor_operation," - ",arithmetic,"is ", floor(floor_operation) - arithmetic)
elif question.lower() == "n":
print("The floor of ",compute,"is ", floor(compute))
else:
print("Unknown response, please try again")
question = input("Would you like to add or subtract a number?: (Y/N) ")
print("Unknown response, please try again")
response = input("What would you like to do?: ")
main()
|
3427274e83c07d602e0ebfb5a6138f9fbccf1447 | joshrwhite/ECE-20875---Python-for-Data-Science | /homework2-gferrara-purdue-master/homework2.py | 1,867 | 3.8125 | 4 | #!/usr/bin/python3
def histogram(data, n, l, h):
hist = list()
for i in data:
if not (isinstance(i,float) or isinstance(i,int)):
print('Error in format of data. Non-float element found.')
return hist
if not (isinstance(n, int) and (n > 0)):
print('Variable "n" is not a positive integer.')
return hist
if not (h >= l):
print('Upper bound is not greater than lower bound.')
return hist
hist = [0] * n
w = (h - l) / n
for i in data:
if (i <= l) or (i >= h):
continue
test = int((i - l) // w)
hist[int((i - l) // w)] += 1
return hist
def addressbook(name_to_phone, name_to_address):
address_to_all = dict()
for name,address in name_to_address.items():
number = name_to_phone[name]
if not address in address_to_all.keys():
address_to_all[address] = ([name], number)
else:
address_to_all[address][0].append(name)
print(f'Warning: Multiple names found for {address}. ', end="")
print(f'Discarding the number for {name} and keeping {address_to_all[address][0][0]}.')
return address_to_all
if __name__ == "__main__":
data = [-2, -2.2, 0, 5.6, 8.3, 10.1, 30, 4.4, 1.9, -3.3, 9, 8]
hist = histogram(data, 10, -5, 10)
print('Test 1: ', end="")
print(hist)
name_to_phone = {'alice': 5678982231, 'bob': '111-234-5678', 'christine': 5556412237, 'daniel': '959-201-3198',
'edward': 5678982231}
name_to_address = {'alice': '11 hillview ave', 'bob': '25 arbor way', 'christine': '11 hillview ave',
'daniel': '180 ways court', 'edward': '11 hillview ave'}
address_to_all = addressbook(name_to_phone, name_to_address)
print(address_to_all)
|
318079ddb197fa950ff07adc50c09fa069a0cca5 | ddascola/hello-world | /Lektion2/2.3.py | 257 | 3.875 | 4 | Number1 = input("Please write a number for calculation:")
Number2 = input("Please write another number for calculation:")
Number11 = int(Number1)
Number22 = int(Number2)
Result = Number11 + Number22
print(f"The sum of {Number11} and {Number22} is {Result}") |
dd25eb37231c22a075dc5c5cb4cabc182537b08e | tollo/ICPP | /find_extreme_divisors.py | 1,506 | 4.125 | 4 | # Find common divisors of two numbers
# Introduction to Compututation and Programming uising Python
d = {}
for x in 'ab':
# Error handling for data types other than 'int'
while True:
try:
input_value = int(input('Integer_' + str(x) + ': '))
break
except ValueError:
print('Please enter only integers')
d['Integer_{0}'.format(x)] = input_value
def findExtremeDivisors(n1, n2):
"""Assumes that n1 and n2 are positive integers
Returns a tuple containing the smallest common divisor > 1
and the largest common divisor of n1 and n2"""
# divisors = () # the empty tuple
minVal, maxVal = None, None
for i in range(2, min(n1, n2) + 1):
if n1 % i == 0 and n2 % i == 0:
if minVal is None or i < minVal:
minVal = i
if maxVal is None or i > maxVal:
maxVal = i
return (minVal, maxVal)
minDivisor, maxDivisor = findExtremeDivisors(d['Integer_a'], d['Integer_b'])
print(minDivisor)
print(maxDivisor)
# def findDivisors(n1, n2):
# """Assumes that n1 and n2 are positive integers
# Returns a tuple containing all common divisors of n1 and n2"""
# divisors = () # the empty tuple
# for i in range(1, min(n1, n2) + 1):
# if n1 % i == 0 and n2 % 1 == 0:
# divisors = divisors + (i,)
# return divisors
#
# divisors = findDivisors(20, 100)
# print(divisors)
# total = 0
# for d in divisors:
# total += d
# print(total)
|
d3d5e55b00d9c7d6fe89fa9a10379ea7c7b5d59d | RYO515/test | /for.py | 1,196 | 3.84375 | 4 | last_names = ['今西', '佐藤', '鈴木', '田中']
first_names = ['航平', '謙介', '康二', '康介']
# print(last_names[0] + first_names[0] + 'さん')
# print(last_names[1] + first_names[1] + 'さん')
# print(last_names[2] + first_names[2] + 'さん')
# print(last_names[3] + first_names[3] + 'さん')
for i in range(len(last_names)):
print(last_names[i] + first_names[i] + 'さん')
# zip(a, b) で複数のリストの要素を同時に取得
# 3つ以上のリストから要素を取り出すことも可能
for last_name, first_name in zip(last_names, first_names):
print(last_name + first_name + 'さん')
# print('出席番号', 0, '番目の' + last_names[0] + 'さん')
# print('出席番号', 1, '番目の' + last_names[1] + 'さん')
# print('出席番号', 2, '番目の' + last_names[2] + 'さん')
# print('出席番号', 3, '番目の' + last_names[3] + 'さん')
for i in range(len(last_names)):
print('出席番号', [i], '番目の' + last_names[i] + 'さん')
# enumerate リストの「要素番号」と「要素」を同時に取得
for num, last_name in enumerate(last_names):
print('出席番号', num, '番目の' + last_name + 'さん') |
b474fd141e689d63b921d035fdc99c2bbc1ace83 | JakeColtman/BayesianBats | /Maze.py | 1,264 | 3.90625 | 4 | import numpy as np
import random
from matplotlib import pyplot as plt
def random_square(maze):
x, y = random.randint(1, maze.shape[0] - 2), random.randint(1, maze.shape[0] - 2)
return [x, y]
def display_maze(maze):
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.pcolor(maze)
plt.show(block=False)
class Maze:
def __init__(self, size):
self._generate_maze(size)
self.exitPos = random_square(self.maze)
self.maze[self.exitPos[0], self.exitPos[1]] = 2
def value_at_point(self, position):
return self.maze[position[0], position[1]]
def set_value_at_point(self, position, value):
self.maze[position[0], position[1]] = value
def next_point_in_direction(self, point, direction):
if direction == "right":
return [point[0] + 1, point[1]]
if direction == "left":
return [point[0] - 1, point[1]]
if direction == "down":
return [point[0], point[1] + 1]
if direction == "up":
return [point[0], point[1] - 1]
def _generate_maze(self, size):
base = np.zeros((size, size))
base[:, 0] = 1
base[0, :] = 1
base[-1, :] = 1
base[:, -1] = 1
self.maze = base
|
0f054f6919ab29c17471b8bb3c0e84f4ad566f00 | vineetkr7/Google-Kickstart-Round-G-2021 | /dogs_and_cats.py | 5,049 | 3.75 | 4 | '''
Problem
You work for an animal shelter and you are responsible for feeding the animals. You already prepared D portions of dog food and C portions of cat food.
There are a total of N animals waiting in a line, some of which are dogs and others are cats. It might be possible that all the animals in the line are dogs or all the animals are cats. A string S of N characters C and D represents the order of cats and dogs in the line. The i-th character is equal to C if the i-th animal in the line is a cat. Similarly, the i-th character is equal to D if the i-th animal in the line is a dog.
The animals are fed in the order they stay in the line. Each dog eats exactly 1 portion of dog food and similarly each cat eats exactly 1 portion of cat food. Moreover, you have extra portions of cat food. Every time a dog eats food, you bring M extra portions of cat food for cats.
Animals have to be fed in the order they wait in line and an animal can only eat if the animal before it has already eaten. That means that if you run out of dog (or cat) food portions and a dog (or a cat) is about to get fed, the line will not move, as all the animals will wait patiently.
You need to determine if in this scenario all the dogs in the line will be fed. Note that this means that some cats might remain in the line, but worry not, you will eventually feed them later!
Input
The first line of the input gives the number of test cases, T. T test cases follow.
The first line of each test case contains four integers N, D, C, and M: the number of animals, the initial number of dog food portions, the initial number of cat food portions, and the additional portions of cat food that we add after a dog eats a portion of dog food, respectively.
The next line contains a string S of length N representing the arrangement of animals.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is YES if all the dogs will be fed and NO otherwise.
Limits
Memory limit: 1 GB.
1≤T≤100.
1≤N≤104.
0≤D,C≤106.
S consists of only characters C and D.
Test Set 1
Time limit: 20 seconds.
M=0
Test Set 2
Time limit: 40 seconds.
0≤M≤106.
Sample
Note: there are additional samples that are not run on submissions down below.
Sample Input
3
6 10 4 0
CCDCDD
4 1 2 0
CCCC
4 2 1 0
DCCD
Sample Output
Case #1: YES
Case #2: YES
Case #3: NO
In Sample Case #1, there are 10 portions of dog food and 4 portions of cat food.
The first two animals are cats, so after they eat, 2 portions of cat food remain.
Then a dog eats one portion of dog food. Now, there are 9 portions of dog food left.
Next, a cat eats a portion of cat food, reducing the number of portions of cat food to 1.
The last two animals are dogs and they each eat one portion of dog food.
So in this case, all the dogs are able to eat.
In Sample Case #2, there are no dogs. Hence, all (zero) dogs will be able to eat trivially.
In Sample Case #3, the cat before the second dog will not be able to eat because there will not be enough portions of cat food. Hence, the second dog will also not eat.
Additional Sample - Test Set 2
The following additional sample fits the limits of Test Set 2. It will not be run against your submitted solutions.
Sample Input
2
12 4 2 2
CDCCCDCCDCDC
8 2 1 3
DCCCCCDC
Sample Output
Case #1: YES
Case #2: NO
In Sample Case #1, 2 portions of cat food appear whenever a dog eats a portion of dog food.
After the first cat eats, there is 1 portion of cat food left.
Then a dog eats, leaving 3 portions of dog food and 3 portions of cat food.
After the next 3 cats eat, there are 3 portions of dog food and 0 portions of cat food remaining.
Then a dog eats, leaving 2 portions of dog food and 2 portions of cat food.
After the next 2 cats eat food, there are 2 portions of dog food and 0 portions of cat food left.
Now a dog eats, leaving 1 portion of dog food and 2 portions of cat food.
Next a cat eats, leaving 1 portion of dog food and 1 portion of cat food.
The last dog eats the remaining portion of dog food.
So in this case, all the dogs are able to eat.
In Sample Case #2, the cat before the second dog will not be able to eat because there will not be enough portions of cat food.
'''
def dogsandcats(d,c,m,order):
if 'D' not in order:
return 'YES'
elif order.count('D') > d:
return 'NO'
else:
for i in range(len(order)):
if order[i] == 'D':
d -= 1
c += m
elif order[i] == 'C':
c -= 1
if c < 0 and 'D' in order[i+1:]:
return 'NO'
if d >= 0:
return 'YES'
if __name__ == '__main__':
t = int(input())
ans = []
for i in range(t):
n,d,c,m = map(int, input().split())
order = input()
ans.append(dogsandcats(d,c,m,order))
for i in range(t):
print(f"Case #{i+1}: {ans[i]}") |
8669bd3a222cad93f36688d7fc45663ae0314c0d | DmitryVGusev/Python_lessons_basic | /lesson03/home_work/hw03_normal.py | 6,286 | 4.46875 | 4 | # Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
"""
Предположим, что при обращении к ряду Фибоначчи, счет начинают все же с первого элемента, а не с нулевого
"""
def fibonacci(n: int, m: int):
"""
Функция, возращающая список из ряда Фибоначчи с n по m элемент
:param n: первый элемент списка
:param m: последний элемент списка
:return: list
"""
result = [1, 1]
position = 2
if n < 1:
return None
if n > m:
return None
while position < m:
result.append(sum([result[-1], result[-2]]))
position += 1
return [result[x] for x in range(n-1, m)]
# Проверка результата
print(fibonacci(3, 6)) # return [2, 3, 5, 8]
print(fibonacci(0, 2)) # return None
print(fibonacci(-1, 20)) # return None
print(fibonacci(5, 4)) # return None
print(fibonacci(6, 6)) # return [8]
# Задача-2:
# Напишите функцию, сортирующую принимаемый список по возрастанию.
# Для сортировки используйте любой алгоритм (например пузырьковый).
# Для решения данной задачи нельзя использовать встроенную функцию и метод sort()
"""
Любой - так любой. Всегда мечтал реализовать рандомную сортировку =)
"""
from random import randint
def sort_to_max(origin_list:list):
"""
Рандомная сортировка. Кажды раз меняет элементы местами до тех пор пока список не окажется отсортированным
:param origin_list: список элементов
:return: отсортированный список элементов
"""
def is_sorted(l):
"""Проверяет отсортирован ли массив"""
return all(l[i] <= l[i+1] for i in range(len(l)-1))
result = origin_list
iterations = 0 # Чисто удовольствия ради. Счетчик количества перетасовок
# Бесконечный цикл пока итоговый список не окажется отсортирован
while not is_sorted(result):
iterations += 1
# чтобы не испортить исходный список, создаем его копию
elements_list = origin_list.copy()
result = []
while len(elements_list) > 0:
# Вытаскиваем случайный элемент из списка и записываем в итоговый список
result.append(elements_list.pop(randint(0, len(elements_list)-1)))
print("Список отсортирован всего за {} попыток".format(iterations))
return result
print(sort_to_max([2, 10, -12, 2.5, 20, -11, 4, 4, 0]))
# Задача-3:
# Напишите собственную реализацию стандартной функции filter.
# Разумеется, внутри нельзя использовать саму функцию filter.
def my_filter(func, lst: list):
"""
Самописный метод реализации filter
:param func: любая функция, возвращающая True или False
:param lst: список
:return: В отличие от классического filter, возвращает List а не filter object
"""
result = []
for i in lst:
if func(i):
result.append(i)
return result
# Проверка результата
print(my_filter(lambda x: x > 0, [-1, 4, -4, 5])) # return [4, 5]
# Задача-4:
# Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4).
# Определить, будут ли они вершинами параллелограмма.
from math import sqrt
def is_parallelogram(A1: list, A2: list, A3: list, A4: list):
"""
Функция, возвращающая True если по четырем заданным точкам можно построить параллелограм
:param A1: список координат [x, y]
:param A2: список координат [x, y]
:param A3: список координат [x, y]
:param A4: список координат [x, y]
:return: True or False
"""
def middle_dot(dot1, dot2):
"""
Функция вычисляющая координаты середины отрезка из двух его точек
:param dot1: список координат [x, y]
:param dot2: список координат [x, y]
:return: список координат [x, y]
"""
x = (dot1[0] + dot2[0]) / 2
y = (dot1[1] + dot2[1]) / 2
return [x, y]
dots_list = [A1, A2, A3, A4]
# Проверка если какие-либо точки совпадают
if any(dots_list.count(i) != 1 for i in dots_list):
return False
"""
По геометрии, у параллелограмма диагонали точкой пересечения делятся на 2.
Мы не знаем порядок точек, так что попарно ищем серединную точку и записываем в список
"""
middle_dots = []
while len(dots_list) > 1:
dot = dots_list.pop(0)
for i in dots_list:
middle_dots.append(middle_dot(dot, i))
# Если в списке находятся две одинаковых точки, то это диагонали параллелограмма
for d in middle_dots:
if middle_dots.count(d) == 2:
return True
return False
A1 = [0, 0]
A2 = [6, 4]
A3 = [5, 0]
A4 = [1, 4]
print(is_parallelogram(A1, A2, A3, A4))
|
d21e722228887c777b7128d97345b9bdcd63f66c | monishnarendra/Python_Programs | /QuickSort.py | 606 | 3.921875 | 4 | import random
def quicksort(list1):
if len(list1) > 1:
high,low,equal=[],[],[]
pivot = list1[0]
for i in list1:
if pivot < 0:
low.append(i)
if pivot == 0:
equal.append(i)
if pivot > 0:
high.append(i)
return quicksort(low)+equal+quicksort(high)
else:
return list1
n = int(input("Enter the number of elements"))
x = int(input("Enter the range"))
list1=[]
for i in range(n):
list1.append(int(random.random()*x))
print(list1)
print(quicksort(list1)) |
e69cc88c8f710afcec7b8925bf0fcde3f13de5e7 | roynitin710/gussing_game-python | /guessing.py | 407 | 3.984375 | 4 | import random
Name=input("Enter your name= ")
secret_no= random.randint(0,9)
guess_count=0
guess_limit=3
while guess_count < guess_limit:
guess_count +=1
guess_no = int(input(f"Guess the no. (between 0 and 9)="))
if guess_no == secret_no:
print(f'{Name} You Won, {secret_no} is the secret no.')
break
else:
print(f'{Name} you lost. {secret_no} is the secret no.') |
f09d0eb2a400dbdab893db63444ab64fad72833e | wxmsummer/algorithm | /leetcode/hot/98_isValidBST.py | 1,256 | 3.515625 | 4 | class Solution:
def isValidBST(self, root:TreeNode) -> bool:
# 判断以node为根节点的子树,其子树中所有的值是否都在(low, up)范围内
def helper(node, low = flaot('-inf'), up = float('inf')):
if not node:
return True
val = node.val
# 如果
if val <= low or val >= up:
return False
# 判断右子树的值是否都大于val
if not helper(node.right, val, up):
return False
# 判断左子树的值是否都小于lval
if not helper(node.left, low, val):
return False
return True
return helper(root)
def isValidBST(self, root:TreeNode) -> bool:
stack = []
p = root
# pre 记录当前节点的前一节点,用于数据比较
pre = None
while p or stack:
print('p:', p)
# 先往左
while p:
stack.append(p)
p = p.left
p = stack.pop()
# 进行判断
if pre and root.val <= pre.val:
return False
#
pre = p
p = p.right
return True |
a5ab0ce6e43243dea907bc427f774bc56e819145 | TrialAnd404/ShowAndTell | /ArtificialIntelligence/mailClassifier.py | 34,019 | 3.828125 | 4 | #!/usr/bin/env python
import math
import sys
import os
import argparse
from collections import Counter, defaultdict
import pickle
import nltk
import re
import csv
"""
text Classifier
-------------------------
a small interface for document classification. Implement your own Naive Bayes classifier
by completing the class NaiveBayestextClassifier below.
utilizing:
nltk:
a tokenizing library that transforms single strings into token lists presumably using unicorn-magic
sets:
a set is a type of list, that can hold only one of each entry.
a list [1,1,2,2,3,3] would result in the set [1,2,3]
to get a set from a list, we call set(myList)
dictionaries:
a dictionary is a key-value list.
essentially, this means that a dictionary might look like this:
myDictionary {
car : Toyota
price : 10000
mileage: 120000
}
but values are not restricted to just numbers or strings. it is possible to fabricate more elaborate
dictionaries with sub-dictionaries as values for keys, for example:
myDictionary {
Vanessa : {
car : Toyota
price : 10000
mileage : 120000
}
Maria : {
car : BMW
price : 20000
mileage : 80000
}
}
a single key can only be present ONCE in a dictionary (unique). as seen above, each subdirectory has only
one key called car, the big surrounding directory has keys Vanessa and Maria.
to access a value we use myDictionary.get(myKey).
if we are not sure whether the key exists, we can use ...get.(myKey, defaultValue) to always be presented with
a default value in case we have no such key (yet) in our dictionary.
"""
class NaiveBayestextClassifier:
def __init__(self):
# self.model = None
"""
our program starts with a little bit of setup.
if on program start there is a file called classifier.pkl,
we read it and load our model from it.
this only happens, if --train has been called previously.
otherwise, this step is skipped
"""
self.model = {}
if os.path.isfile('classifier.pkl'):
with open('classifier.pkl', 'rb') as file:
self.model = pickle.load(file)
def calculateChi(self, c1_w, c2_w, c1_not_w, c2_not_w):
# print(c1_w, c2_w, c1_not_w, c2_not_w)
"""
this function is used to calculate the 2x2matrix and the according chi-squared value of a word.
it accepts the values of the matrix by row, meaning:
c1_w | c2_w
|
-------------------
c1_not_w| c2_not_w
|
where c1_w is the amount of ham-mails containing the word w, and c1_not_w is the amount
of ham-mails NOT containing the word w.
c2_w and c2_not_w are essentially the same metric, but concerning spam instead of ham mails.
in order to keep the calculation readable and close to the paper,
numerous helping variables are calculated first, which is not necessary in theory.
after that the calculation of the chi-squared value is done as shown in the paper.
for testing, the example matrix from the paper was used, replicating the chi-squared value of ~8.10.
we can also see, that tokens that appear in all spam and ham mails will essentially break
the formula. we COULD try to mitigate this with checks:
basically if a column sum or a row sum is zero (-> calculation would fail) we just return 0 as our chi value
since this occurs only for the token "subject" in this case, this step is skipped
"""
W1 = c1_w + c2_w
W2 = c1_not_w + c2_not_w
C1 = c1_w + c1_not_w
C2 = c2_w + c2_not_w
N = W1 + W2
M = [[c1_w, c2_w], [c1_not_w, c2_not_w]]
W = [W1, W2]
C = [C1, C2]
chi = 0
"""
this is bascially the formula given on the paper. for all column sums, calculate chi value with all row sums
-> we iterate through both in 2 for loops.
"""
for i in range(len(M)):
for j in range(len(M[0])):
E = (W[i] * C[j]) / N
chi += (M[i][j] - E) ** 2 / E
return chi
# classifier.train(tokens_all_classes: token->amount, tokens_specific_genre: genre->token->amount])
def train(self, spamMails, hamMails):
"""
:param spamMails : the list of (previoulsy tokenizend + lowercased + set-ed) spam mails
:param hamMails : the list of (previoulsy tokenizend + lowercased + set-ed) ham mails
this function serves as the main training function in which the model for the classifier is generated & saved.
in order to save it in the general directory, where this script is located aswell, we must first move 3 steps
down, as the initial --train call moves to the training data which is 3 directories deep.
"""
os.chdir('../../../') # we move down 3 steps
location = os.getcwd() # and reset our locatiom to where we are now
print("saving model to ", location)
"""
we want to know with which words we are working with, for that we use a set,
in which every value can only occur once.
this serves the purpose of getting rid of duplicates:
mail1 : "i am an apple"
mail2 : "i am a horse"
these mails will result in a bag of words like this:
i, am, an, apple, a, horse
=> even though "i" and "am" occur in both mails, they only get added to our bag of words once.
NOTE: we will later filter the entries of our bag of words.
some tokens will contain letters we dont want to use, like punctuation or special characters.
this makes for a pretty big performance overhead tha could
be adressed after finalizing the classifier and is a worthy TODO
"""
bagOfWords = set()
"""
we are using a dictionary for our model.
the rough shape of our model will look something like this:
classifierModel[
spam_count :
-> total number of spam mails
ham_count :
-> total number of ham mails
priors [
spam :
-> the calculated spam prior
(spamMails / totalMails)
ham :
-> the calculated ham prior
(hamMails / totalMails)
]
vocabulary[
token1[
ham_occurences :
-> amount of hamMails containing this token
spam_occurences :
-> amount of spamMails containing this token
total :
-> total occurences of thia token
p_ham :
-> possibility of this token occuring in a hamMail
p_spam :
-> possibility of this token occuring in a spamMail
chi :
-> the chi value of this token
]
token2[
... see above
]
...
]
]
as shown above, the model is a dictionary with several sub-dictionaries
"""
classifierModel = defaultdict(dict)
classifierModel["spam_count"] = len(spamMails)
classifierModel["ham_count"] = len(hamMails)
classifierModel["priors"]["spam"] = classifierModel.get("spam_count") / (
classifierModel.get("spam_count") + classifierModel.get("ham_count"))
classifierModel["priors"]["ham"] = classifierModel.get("ham_count") / (
classifierModel.get("spam_count") + classifierModel.get("ham_count"))
"""
for unknown reasons, we have to instanciate our vocabulary dictionary seperately and later put it into our model
"""
vocabulary = defaultdict(dict)
"""
we now iterate the previously (immediately after reading the 'train' agrument)
tokenized mails and add all tokens to our bag of words.
NOTE: this is where we might be able to optimize some things in the future.
we have code complexity O(n) for the creation of our bag of words,
and then O(n²) for the creation of our vocabulary since we iterate both our generated bagOfWord
and our mails.
this is straight up useless, but it works. What we could do, is instead of generating a bag of words that we
later do not use anymore, just immediately put the token in our vocabulary.
This would bypass the initial O(n) complexity of generating the bagOfWords.
but again this solution makes for a little easier to read code.
"""
for mail in hamMails:
for token in mail:
bagOfWords.add(token)
for mail in spamMails:
for token in mail:
bagOfWords.add(token)
"""
we now iterate our bag of words and check for letters other than a-z,
if the token contains anything else it gets tossed and is subsequently ignored.
this is so for example the token " 've " that occurs unproportionally often or the token " @ " get ignored,
and we are left only with easy-to-read, lowercased tokens that do not contain special characters
"""
for token in bagOfWords:
if re.search("^[a-z]*$", token) and token != "subject":
for mail in hamMails:
"""
if a token is accepted, we then check if it comes from a spam or ham mail,
and increment the according value in our token accordingly.
this checkup is admittedly VERY slow, but it is easy to understand and read
sidenote:
since we iterate all tokens, and then all mails,
the complexity of this step alone is O(n²)
(potentially n tokens * potentially n mails = n² complexity)
"""
if token in mail:
vocabulary[token]["ham_occurences"] = vocabulary[token].get("ham_occurences", 0) + 1
for mail in spamMails:
if token in mail:
vocabulary[token]["spam_occurences"] = vocabulary[token].get("spam_occurences", 0) + 1
"""
last we calculate the total occurences of our token
"""
vocabulary[token]["total"] = vocabulary[token].get("ham_occurences", 0) + vocabulary[token].get(
"spam_occurences", 0)
for token in vocabulary.keys():
"""
we have now successfully counted all out tokens, and can now calculate their
individual propabilities of being in a spam or ham mail.
the formula is:
(occurences in ham) / (number of ham mails)
equivalent for spam
"""
# print(token)
vocabulary[token]["p_ham"] = vocabulary[token].get("ham_occurences", 0) / len(hamMails)
vocabulary[token]["p_spam"] = vocabulary[token].get("spam_occurences", 0) / len(spamMails)
"""
lastly we calculate the chi value of our token.
we use:
...get("spam_occurences",0) to make sure we get at least the value 0,
since some tokens might not have occured in spam mails,
therefore they do not possess a key called "spam_occurences".
this 'hacky' way ensures we always pass values to our chi function and do not break here.
"""
# print(token)
vocabulary[token]["chi"] = self.calculateChi(
vocabulary[token].get("ham_occurences", 0),
vocabulary[token].get("spam_occurences", 0),
len(hamMails) - vocabulary[token].get("ham_occurences", 0),
len(spamMails) - vocabulary[token].get("spam_occurences", 0)
)
"""
this lambda expression sorts our vocabulary into a list object by a value in its nested dictionary,
as per the python3 documentation. example: https://careerkarma.com/blog/python-sort-a-dictionary-by-value/
it is sorted in reverse, so the big values get sorted to the front.
after this we can simply grab the first N values from the list.
"""
sorted_vocabulary = sorted(vocabulary.items(), key=lambda x: (x[1]['chi']), reverse=True)
N = 100
print("CHI PLACEMENTS 1-100:")
for i in range(N):
print(sorted_vocabulary[i])
print("CHI PLACEMENTS 101-200")
for i in range(N):
print(sorted_vocabulary[i + 100])
print("CHI PLACEMENTS 201-300")
for i in range(N):
print(sorted_vocabulary[i + 200])
print("place 300 for testing:")
print(sorted_vocabulary[299])
# various testing outputs
# print(vocabulary["free"]
# print(self.calculateChi(10,1,50,59))
"""
finally our vocabulary is completely done, and we dump it in our model.
why this does not work "natively" is beyond me.
this little workaround solves all problems we have when trying to build the
vocabulary in one step.
"""
classifierModel["vocabulary"] = vocabulary
classifierModel["100"] = sorted_vocabulary[:100]
classifierModel["200"] = sorted_vocabulary[:200]
classifierModel["300"] = sorted_vocabulary[:300]
classifierModel["sorted"] = sorted_vocabulary
# for token in classifierModel["100"]:
# print(token[0])
# print(classifierModel)
"""
now we save our model to a binary file where we can read it when needed in the future
"""
with open('classifier.pkl', 'wb') as file:
pickle.dump(classifierModel, file)
def test(self, spamMails, hamMails):
print("test starting")
def apply(self, spamMails, hamMails):
"""
:param spamMails: a list containing all spam mails we want to classifiy
:param hamMails: a list containing all ham mails we want to classifiy
:return: empty
the following declarations are a rather "useless" overhead that we dont necessarily need.
since we want to use our classifier on several different sets of tokens and compare the results,
it is nicer to have all values printed at the same time later. this, sadly, means that it is much more
conventient to just declare a whole bunch of variables here, so we can later print them all at once.
"""
correctSpam100 = 0
correctHam100 = 0
incorrectSpam100 = 0
incorrectHam100 = 0
correctSpam200 = 0
correctHam200 = 0
incorrectSpam200 = 0
incorrectHam200 = 0
correctSpam300 = 0
correctHam300 = 0
incorrectSpam300 = 0
incorrectHam300 = 0
correctSpamTotal = 0
correctHamTotal = 0
incorrectSpamTotal = 0
incorrectHamTotal = 0
total = 0
totalSpam = 0
totalHam = 0
"""
since in theory, the propability of any token to be in a spam mail can never be 0, we introduce a "backup" valie called epsilon here.
this is a so called superparameter we can adjust after/during training, to make the model more accurate.
this superparameter has not been updated during training. we COULD automate this propably, by having the code
run several times and adjust this parameter itself.
"""
epsilon = 0.0001
"""
here starts the copy paste fiesta. it is simply a matter of laziness why this code has not been
moved to a seperate function where it would look much cleaner.
"""
###### FIRST WE ITERATE THROUGH KNOWN HAM MAILS AND COMPARE RESULTS
for mail in hamMails:
"""
this for loop iterates over all hamMails and checks if a the single current mail is more
likely to be a spam or a ham mail, by checking if the tokens in our vocabulary do or dont occur
in the mail.
the same happens later on with spamMails.
"""
total += 1
totalHam += 1
p_spam = 0
p_ham = 0
"""
first we add the priors for spam and ham, since those get added anyways.
since the numbers get too small when mulitplying propabilities
python would eventually simply round the result down to 0.
instead we calculate in log space and just add the logarithmic values
-> see: log(a*b) = log(a) + log(b)
since we only care about the "bigger picture", to check if a mail is
more likely to be spam over ham we can still check which of the values is bigger since:
if
a*b < c*d <-- "conventional" handling of propabilities
it is also true that:
log(a*b) < log(c*d) <-- same calculation, but in log space
= log(a) + log(b) < log(c) + log (d)
thus, calculating in log space is beneficial for us
"""
p_ham += math.log2(self.model["priors"]["ham"])
p_spam += math.log2(self.model["priors"]["spam"])
for entry in self.model["sorted"][:100]:
"""
this loop (aswell as all other similar loops from here on) iterates over all selected tokens,
in this case the best 100 tokens by chi value.
"""
token = entry[0]
"""
we check for all tokens if they occur in our mails we want to classify.
if yes -> p_spam and p_ham of the current token get added to our propabilities,
if not the opposite porpabilities, meaning 1-p_spam/ham get added
"""
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
"""
our first 100 tokens have been iterated. we stop and check for each mail if the classification is indeed
correct, and increment the respective helper variables declared at the start of the apply function.
"""
# print("p_ham: %d, p_spam: %d" % (p_ham, p_spam))
if p_spam > p_ham:
# print("Prediction: Mail " + mail[1] + " is Spam")
incorrectHam100 += 1
else:
# print("Prediction: Mail " + mail[1] + " is Ham")
correctHam100 += 1
# print("actual class: Ham")
"""
now we want to see what the result would have been if we use the 200 best tokens. we already have a p_ham
and p_spam for the best 100 tokens, so we do not need to reset here, we can just keep going and load the
next 100 tokens.
"""
for entry in self.model["sorted"][100:200]:
token = entry[0]
"""
same procedure as before. we check the new tokens and increment our p_ham / p_spam accordingly.
"""
# print(p_ham)
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
"""
the values of the tokens 100-200 have been added to the p_ham / p_spam values. we can now check again
and track our results in seperate variables.
"""
# print("p_ham: %d, p_spam: %d" % (p_ham, p_spam))
if p_spam > p_ham:
# print("Prediction: Mail " + mail[1] + " is Spam")
incorrectHam200 += 1
else:
# print("Prediction: Mail " + mail[1] + " is Ham")
correctHam200 += 1
# print("actual class: Ham")
for entry in self.model["sorted"][200:300]:
token = entry[0]
"""
same idea as before, we want the values for p_ham and p_spam for the best 300 tokens, we do already have
results for the best 200, so we can just keep using those.
"""
# print(p_ham)
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
"""
again all tokens from 200-300 have been iterated, and we check if the current mail is more likely to be
spam or ham.
"""
# print("p_ham: %d, p_spam: %d" % (p_ham, p_spam))
if p_spam > p_ham:
# print("Prediction: Mail " + mail[1] + " is Spam")
incorrectHam300 += 1
else:
# print("Prediction: Mail " + mail[1] + " is Ham")
correctHam300 += 1
# print("actual class: Ham")
"""
as a bonus we now repeat the procedure for all remaining tokens
"""
for entry in self.model["sorted"][300:]:
token = entry[0]
# print(p_ham)
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
"""
the entirety of our known vocabuöary has been iterated and any token occuring
(or not occuring) in our mail has contributed to a p_ham and p_spam value for our single current mail.
"""
# print("p_ham: %d, p_spam: %d" % (p_ham, p_spam))
if p_spam > p_ham:
# print("Prediction: Mail " + mail[1] + " is Spam")
incorrectHamTotal += 1
else:
# print("Prediction: Mail " + mail[1] + " is Ham")
correctHamTotal += 1
"""
now we repeat the procedure for all mails in our spam mail list to see if our classifier will indeed
recognize them as spam mails.
"""
###### NOW WE ITERATE KNOWN SPAM MAILS & CHECK
for mail in spamMails:
total += 1
totalSpam += 1
p_spam = 0
p_ham = 0
"""
adding priors, setting up small debug variables..
"""
p_ham += math.log2(self.model["priors"]["ham"])
p_spam += math.log2(self.model["priors"]["spam"])
for entry in self.model["sorted"][:100]:
token = entry[0]
"""
checking the first 100 tokens
"""
# print(p_ham)
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
"""
checking if mail is currently classified as spam (would be correct, since is a known spam mail)
"""
# print("p_ham: %d, p_spam: %d" % (p_ham, p_spam))
if p_spam > p_ham:
# print("Prediction: Mail " + mail[1] + " is Spam")
correctSpam100 += 1
else:
# print("Prediction: Mail " + mail[1] + " is Ham")
incorrectSpam100 += 1
# print("actual class: Ham")
for entry in self.model["sorted"][100:200]:
token = entry[0]
"""
checking for tokens 100-200
"""
# print(p_ham)
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
if p_spam > p_ham:
correctSpam200 += 1
else:
incorrectSpam200 += 1
for entry in self.model["sorted"][200:300]:
token = entry[0]
"""
checking for tokens 200-300
"""
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
if p_spam > p_ham:
correctSpam300 += 1
else:
incorrectSpam300 += 1
for entry in self.model["sorted"][300:]:
token = entry[0]
"""
checking for complete rest of tokens
"""
# print(p_ham)
if token in mail[0]:
p_ham += math.log2(max(self.model["vocabulary"][token]["p_ham"], epsilon))
p_spam += math.log2(max(self.model["vocabulary"][token]["p_spam"], epsilon))
else:
p_ham += math.log2(
max(1 - self.model["vocabulary"][token]["p_ham"], epsilon)
)
p_spam += math.log2(
max(1 - self.model["vocabulary"][token]["p_spam"], epsilon)
)
# print("p_ham: %d, p_spam: %d" % (p_ham, p_spam))
if p_spam > p_ham:
# print("Prediction: Mail " + mail[1] + " is Spam")
correctSpamTotal += 1
else:
# print("Prediction: Mail " + mail[1] + " is Ham")
incorrectSpamTotal += 1
"""
now, all mails have been dissected and checked against our vocabulary with multiple subsets.
we now print our findings, containing the amount of correctly classified mails aswell as the
amount of incorrectly classified mails.
"""
print("100 best tokens classification:")
print("correct: %d spam, %d ham" % (correctSpam100, correctHam100))
print("incorrect: %d spam, %d ham" % (incorrectSpam100, incorrectHam100))
print("200 best tokens classification:")
print("correct: %d spam, %d ham" % (correctSpam200, correctHam200))
print("incorrect: %d spam, %d ham" % (incorrectSpam200, incorrectHam200))
print("300 best tokens classification:")
print("correct: %d spam, %d ham" % (correctSpam300, correctHam300))
print("incorrect: %d spam, %d ham" % (incorrectSpam300, incorrectHam300))
print("all tokens classification:")
print("correct: %d spam, %d ham" % (correctSpamTotal, correctHamTotal))
print("incorrect: %d spam, %d ham" % (incorrectSpamTotal, incorrectHamTotal))
"""
and now, we are finally done
"""
if __name__ == "__main__":
"""
the main program that gets called when executing python3 classifier.py
we have implemented a program that consumes arguments and acts accordingly.
"""
parser = argparse.ArgumentParser(description='A document classifier.')
parser.add_argument(
'--train', help="train the classifier", action='store_true')
"""
the argument "--test" is deprecated and was previously used to test the arg parser
"""
parser.add_argument(
'--test', help="train the classifier (alternative)", action='store_true')
parser.add_argument('--apply', help="apply the classifier (you'll need to train or load"
"a trained model first)", action='store_true')
parser.add_argument('--inspect', help="get some info about the learned model",
action='store_true')
"""
we read the argument and pass it to the variable called args
"""
args = parser.parse_args()
classifier = NaiveBayestextClassifier()
"""
depending on our argument (stored in args variable) we call a different function
"""
if args.train:
"""
first we read both our spam and our ham mails.
to do so, we switch our Current Working Directory (cwd) to the training dataset.
"""
spamMails = []
hamMails = []
os.chdir('corpus-mails/corpus/training')
location = os.getcwd()
"""
now we read all files in our training location.
all subdirs get opened, all files are being read.
"""
for subdir, dirs, files in os.walk(location):
for file in files:
filepath = subdir + os.sep + file
filename = os.path.splitext(file)[0]
f = open(filepath, "r", encoding="utf-8")
filetext = f.read()
tokenized_text = set(nltk.word_tokenize(filetext.lower()))
"""
since the only way to differentiate mails is by name, we check for the filenames starting with 'spmsg'. all those get added to our spam-mail list, the rest to our ham-mail list
"""
if filename.startswith('spmsg'):
spamMails.append(tokenized_text)
else:
hamMails.append(tokenized_text)
f.close()
# cant forget to close our files...
# some debugging output
print("ham mails: ", len(hamMails))
print("spam mails: ", len(spamMails))
# throw it all to our training function
classifier.train(spamMails, hamMails)
if args.apply:
"""
basically the same procedure as with training.
we move to the correct place in our working directory, and read all mails we find there
-> our validation data
"""
spamMails = []
hamMails = []
os.chdir('corpus-mails/corpus/validation')
location = os.getcwd()
for subdir, dirs, files in os.walk(location):
for file in files:
filepath = subdir + os.sep + file
filename = os.path.splitext(file)[0]
f = open(filepath, "r", encoding="utf-8")
filetext = f.read()
tokenized_text = set(nltk.word_tokenize(filetext.lower()))
# print(filename)
if filename.startswith('spmsg'):
spamMails.append((tokenized_text, filename))
else:
hamMails.append((tokenized_text, filename))
f.close()
print("ham mails: ", len(hamMails))
print("spam mails: ", len(spamMails))
classifier.apply(spamMails, hamMails) |
4aa72de6ab4a84d64aa9ebba183f8f840eb14374 | naitik30/learnpythonbyhardway_ex | /ex11.py | 290 | 3.71875 | 4 | print "How old are you?",
age = raw_input()
# 26
print "How tall are you?",
height = raw_input()
# 6
print "How much do you weigh?",
weight = raw_input()
#90
print "So, you're %r old, %r tall and %r heavy." % (
age, height, weight)
# So, you're '26' old, '6' tall and '90' heavy. |
b9262f9c0927b1c8495b802ad0d03c1299633d91 | iafjayoza/Python | /Longest_Common_Subsequence/maximum_subarray.py | 486 | 3.9375 | 4 | # Kadane's algorithm for maximum sub-array problem.
def max_subarray(a):
current_max = global_max = a[0]
subarray = []
for i in range(1,len(a)):
current_max = max(a[i],current_max + a[i])
if current_max > global_max:
global_max = current_max
subarray.append(a[i])
print("Maximum sum of subarray is ",global_max)
print("Maximum subarray is ",subarray)
return (global_max)
a = [1,-3,2,3,1]
b = [-2,3,2,-1]
max_subarray(b)
|
442dc6b6f0272515c10a3591d51be267068174f5 | RaphPortland/easy_pytest | /convertisseurdetemps.py | 877 | 4.21875 | 4 |
def convert_minutes_to_seconds(minutes):
result = minutes * 60;
return result;
def convert_hours_to_minutes(hours):
return hours * 60;
def convert_days_to_hours(days):
return days * 24;
def convert_hours_to_seconds(hours):
return hours * 60 *60;
a = 0;
while(a != 5):
print("1 . convert_minutes_to_seconds")
print("2 . convert_hours_to_minutes")
print("3 . convert_days_to_hours")
print("4 . convert_hours_to_seconds")
print("5 . Quitter")
try :
a = input()
except:
a=5
if a==5:
print("On quitte le programme")
elif a==4:
print("2 hours = " + str(convert_hours_to_seconds(2)) + " seconds")
elif a==3:
print("2 days = " + str(convert_days_to_hours(2)) + " hours")
elif a==2:
print("2 hours = " + str(convert_hours_to_minutes(2)) + " minutes")
elif a==1:
print("2 minutes = " + str(convert_minutes_to_seconds(2)) + " seconds")
|
5e07efd4333f6ae6092a4ad87bb5ca8bb6876591 | Upendradwivedi/random | /game.py | 1,843 | 3.96875 | 4 | print("\t\t\t***************DICE GAME*****************")
print("do you want to continue-:")
ch=input("write Y for yes and N for no-:")
while(ch=='Y'):
i=0
COUNT=0
count=0
while(i<5):
import random
import time
player=random.randint(1,6)
ai=random.randint(1,6)
print("IT'S YOUR CHANCE.....\n YOU ROLLED........")
time.sleep(2)
print("YOU ROLLED",player)
print("IT'S COMPUTER CHANCE.....\n COMPUTER ROLLED.......")
time.sleep(2)
print("computer rolled",ai)
if(player>ai):
print("you win")
COUNT=COUNT+1
if(player<ai):
print("computer win")
count=count+1
while(player==ai):
print("its tie")
print("game again")
import random
import time
player=random.randint(1,6)
ai=random.randint(1,6)
print("IT'S YOUR CHANCE.....\n YOU ROLLED........")
time.sleep(2)
print("YOU ROLLED",player)
print("IT'S COMPUTER CHANCE.....\n COMPUTER ROLLED.......")
time.sleep(2)
print("computer rolled",ai)
if(player>ai):
print("you win")
COUNT=COUNT+1
if(player<ai):
print("computer win")
count=count+1
i=i+1
print("your score is",COUNT)
print("computer score is",count)
if(COUNT>count):
time.sleep(2)
print("you win")
if(COUNT<count):
time.sleep(2)
print("you loose computer win\nbetter luck next time")
print("do you want to continue")
ch=input("write Y for yes and N for no-:")
if(ch=='N'):
print("see you next time")
exit()
|
07f17c08316b044f726206b19c509d3b049c0a6d | Guadalupe-2021/4-en-linea | /4EnLinea.py | 2,774 | 4.0625 | 4 | print("Bienvenido al juego")
movs= int(input("ingrese la cantidad de movimientos(1 movimiento es el del jugador y el del jugador 2): "))
secuencia_1=[]
contador=1
print("ingrese la secuencia")
for contador in range(movs) :
secuencia_1.append (int(input("Ingrese el movimiento del Jugador 1: ")))
secuencia_1.append (int(input("Ingrese el movimiento del Jugador 2: ")))
def tableroVacio():
return [
[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,0,0,0,0,0],
]
def completarTableroEnOrden(secuencia, tablero):
for indice, columna in enumerate(secuencia):
if columna < 7:
if columna >= 1:
fichaNumero= 1+ (indice % 2)
soltarFichaEnColumna(fichaNumero, columna, tablero)
else:
print("La columna debe estar entre 1-7")
return
else:
print("La columna debe estar entre 1-7")
return
return tablero
def soltarFichaEnColumna(ficha, columna, tablero):
for fila in range(6, 0, -1):
if tablero[fila - 1][columna - 1] == 0:
tablero[fila - 1][columna - 1] = ficha
return
def dibujarTablero(tablero):
print(' _ _ _ _ _ _ _ ')
for fila in tablero:
print('|')
for celda in fila:
if celda == 0:
print(' 0 ', end=' ')
else:
print(' %s ' % celda, end=' ')
print('|')
print(' ')
print(' _ _ _ _ _ _ _ ')
tablero1=dibujarTablero(completarTableroEnOrden(secuencia_1, tableroVacio()))
def contenidoColumna(nro_columna,tablero):
columna=[]
for fila in tablero:
celda=fila[nro_columna - 1]
columna.append(celda)
return columna
def llamadoColumna(nro,tablero):
if nro==0:
contenidoColumna(6,tablero)
contenidoColumna(5,tablero)
contenidoColumna(4,tablero)
contenidoColumna(3,tablero)
contenidoColumna(2,tablero)
contenidoColumna(1,tablero)
else:
contenidoColumna(nro,tablero)
def contenidoFila(nro_fila,tablero):
fila=[]
for columna in tablero:
celda=columna[nro_fila - 1]
fila.append(celda)
return fila
def llamadoFila(nro,tablero):
if nro==0:
contenidoFila(6,tablero)
contenidoFila(5,tablero)
contenidoFila(4,tablero)
contenidoFila(3,tablero)
contenidoFila(2,tablero)
contenidoFila(1,tablero)
else:
contenidoFila(nro,tablero)
ver= int(input("Para ver las filas ingrese 1, para ver las columnas ingrese 2, para saltar esto precione otro numero"))
if ver == 1:
num1=int(input("Ingrese 0 para ver todas las filas, o un numero del 1-6 para ver una en concreto"))
if num1 > 6:
print("Numero invalido")
else:
llamadoFila(num1,tablero1)
else:
if ver == 2:
num2=int(input("Ingrese 0 para ver todas las columnas, o un numero del 1-6 para ver una en concreto"))
if num2 > 6:
print("Numero invalido")
else:
llamadoColumna(num2,tablero1)
else:
print("Saltado")
|
39ee7394ef833575d49d448c77c4615b26339723 | neelaryan2/Proof-Reading-Rewriter | /packages/preProcessing/caseCorrector.py | 712 | 3.71875 | 4 | import re
# Written by Niraj Mahajan, Department of Computer Science, IIT Bombay.
# Inputs a list of strings and returns corrections for Case
# This is based on the position of full stops and ^ characters.
# Corrects only the first letter of every sentence
def caseCorrector(in_list):
for i,elem in enumerate(in_list):
if(elem[0].isupper()):
in_list[i] = elem.capitalize()
else:
in_list[i] = elem.lower()
out_list = in_list.copy()
out_list[0] = out_list[0].capitalize()
for i in range(len(out_list)):
if (i == len(out_list)-1):
continue
else:
rex = re.compile(r'[!.?]+$')
found = rex.search(out_list[i]) != None
if(found):
out_list[i+1] = out_list[i+1].capitalize()
return out_list |
333686eb64818cb5c7b151dee465534ac79d45ac | zbhuiyan/SoftDesSp15 | /inclass/oop_practice/solutions/problem3_sol.py | 1,938 | 4.34375 | 4 | """ Practice problems for objects """
from math import sqrt
class PointND(object):
def __init__(self, coordinates):
""" Initialize an n-dimensional point from a list of coordinates.
coordinates: a list of numbers specifying the coordinates of
the point """
self.coordinates = coordinates
def distance(self, other):
""" Compute the Euclidean distance between self and other
other: an n-dimensional pointed represented as a PointND object
returns: the Euclidean distance between the two points.
(assume that the two points have the same number of coordinates)
>>> p1 = PointND([0,3])
>>> p2 = PointND([4,0])
>>> p1.distance(p2)
5.0
"""
accumulator = 0.0
for i in range(len(self.coordinates)):
accumulator += (self.coordinates[i] - other.coordinates[i])**2
return sqrt(accumulator)
def __str__(self):
""" Converts a point to a string
>>> p1 = PointND([4.0, 5.0, 2.0, 1.0])
>>> print p1
(4.0, 5.0, 2.0, 1.0)
"""
return_val = "("
for (i,coord) in enumerate(self.coordinates):
return_val += str(coord)
if i + 1 != len(self.coordinates):
return_val += ", "
return_val += ")"
return return_val
class Point3D(PointND):
def __init__(self,x,y,z):
""" Initialize a Point3D object at position (x,y,z)
x: a number representing the x-coordinate of the point
y: a number representing the y-coordinate of the point
z: a number representing the z-coordinate of the point
>>> p = Point3D(5.0, 7.0, -2.0)
>>> print p
(5.0, 7.0, -2.0)
"""
super(Point3D, self).__init__([x,y,z])
if __name__ == '__main__':
import doctest
doctest.testmod() |
5a6fef06b7bd1b63b1db9ed0f88d767a12b619a9 | tychonievich/cs1110s2017 | /markdown/files/002/write_ex1.py | 4,513 | 4.75 | 5 | # 1. open file
# 2. write something to file --> data are put in buffer
# 3. close the file --> force data to be written to the file
### BE CAREFULE, don't open your program file with a write mode ###
### The content in your program file will be empty ###
# There are several ways to open, write, and close
####################################
### Open and close explicitly and
### write file with write()
####################################
# be careful with the file's name
# open with "w" mode will empty the file's content
outfile = open('data1.txt', 'w')
outfile.write('take one argument of type string')
# outfile.close()
# Without explicitly close the file, it's up to
# the operating system how it will behave at the moment
# i.e., sometimes our code will work but sometimes it won't.
# This is unpredictable.
# Therefore, we should always close the file.
####################################
### Open and close explicitly and
### write file with print()
####################################
# A flexible way to write to file is use "print" instead of "write"
# print() allows us to print multiple things, multiple types to the file
# -- unlike write() that accepts only one thing and it must be string.
#
outfile = open('data2.txt', 'w')
# optional argument file=name_of_file_object -- telling which file to print to
print('any set of values, any type', outfile, file=outfile)
# can print many times
print('string', 197, 9*8, True, '###', file=outfile)
outfile.close()
# sometimes, there might be a problem while writing to file
outfile = open('data3.txt', 'w')
for i in range(4):
number = int(input('Enter an integer: '))
print(number, file=outfile)
outfile.close()
# Suppose when we run this code,
# the user enters an empty space, a letter, or nothing.
# We'll get a runtime error.
# When a runtime error occurs, there is no guarantee
# whether the things we try to write to the file will actually be written.
# This is entirely depending on the operating system.
# Thus, instead of letting the operating system decides what to do,
# we want to take control and make sure data are written to the file.
# To force this writing to the file, we have to make sure
# that the file is always closed.
# One way to handle any potential errors that might occur at runtime
# and make sure the file is close is to use a try/except block
####################################
### Open and close explicitly and
### write file with print()
### Use a try/except block to handle errors
####################################
outfile = open('data3.txt', 'w')
try:
for i in range(4):
number = int(input('Enter an integer: '))
print(number, file=outfile)
outfile.close() # close the file after everything's done
except: # notice we didn't specify the kinds of errors, i.e., handle *any* kinds the same way
outfile.close() # if something goes wrong, close the file
# The "except" clause stops the error and not show error message,
# and then forces the file to close.
# However, if we want information about the error,
# we wouldn't want to stop the error.
# In fact, we want to let the error occurs and shows
# the error message, and also force closing the file.
# To have this behavior, we'd use a finally keyword.
# Let's modify the above code
####################################
### Open and close explicitly and
### write file with print()
### Use a try/finally block to handle errors
####################################
outfile = open('data3.txt', 'w')
try:
for i in range(4):
number = int(input('Enter an integer: '))
print(number, file=outfile)
outfile.close() # close the file after everything's done
finally: # if anything goes wrong, handle it
outfile.close()
# The "finally" clause doesn't stop the error from happening.
# The error message will show. Then the code block of the finally
# clause will be executed (in this example, close the file)
# Make use of a Python's "with" statement
# and thus we don't have to explicitly/manually close the file;
# (the best way to work with file)
# also behave the same way as try/finally example above
####################################
### Use the with statement to open and close file
### write file with print()
####################################
with open('output.txt', 'w') as outfile:
for i in range(4):
number = int(input('Enter an integer '))
print(number, file=outfile)
# guarantee to close the file as the code exit the with block |
74bbc031e83a18db2ed79128f34173b70555089b | gabriellaec/desoft-analise-exercicios | /backup/user_288/ch37_2020_04_08_12_04_51_743382.py | 166 | 3.515625 | 4 | senha = 'desisto'
pergunta = input('Escolha uma palavra: ')
while pergunta != senha:
pergunta = input('Escolha uma palavra: ')
print ('você acertou a senha!') |
8d403a5d079981bbc9f1c2499c8b2e1549cf908b | skJack/MachineLearningByLihang | /Chapter2/Perception.py | 2,070 | 3.53125 | 4 | #!/usr/bin/python
import numpy as np
import random
import matplotlib.pyplot as plt
class Perception:
def __init__(self,max_iter = 10,learning_rate = 1,x_sample = None,y_label = None):
self.max_iter = max_iter
self.learning_rate = learning_rate
self.w = 0
self.b = 0
self.w_list = []
self.b_list = []#存储所有的迭代w,b值,方便观察
self.x_sample = x_sample
self.y_label = y_label
def train(self,x_data,y_label):
self.x_sample = x_data
self.y_label = y_label
self.w = np.zeros(x_data.shape[1])
for i in range(50):
#random_index = random.randint(0,x_data.shape[1])#随机挑选样本
random_index = i%(x_data.shape[1]+1)
wx = np.sum(np.dot(self.w,x_data[random_index]))#需要改成内积数字计算wx的和,作为中间结果
yx = np.dot(x_data[random_index],y_label[random_index])#计算yx 为二维向量
y = y_label[random_index]*(wx+self.b)#当前预测值注意括号
if y<=0:
#未被正确分类,需要修改w,b
self.w = self.w + self.learning_rate*yx
self.b = self.b + y_label[random_index]
self.w_list.append(self.w)
self.b_list.append(self.b)
Perception.print_para(self)
def print_para(self):
print("w = ",self.w)
print("b = ",self.b)
def plot_result(self):
x1 = np.linspace(0, 6, 6) # 在0到6中取6个点
#画点
for i in range(self.x_sample.shape[1] + 1):
plt.text(self.x_sample[i][0], self.x_sample[i][1], str((self.x_sample[i][0], self.x_sample[i][1])), ha='right')
if self.y_label[i]==1:
plt.plot(self.x_sample[i][0], self.x_sample[i][1], 'ro',color = 'red')
else:
plt.plot(self.x_sample[i][0], self.x_sample[i][1], 'ro', color='blue')
plt.xlim(-6, 6)
plt.ylim(-6, 6)
#画分类面
for i in range(len(self.w_list)-1,0,-1):#注意倒序要减一
if self.w_list[i][1] == 0:
continue
y_axis = -self.b_list[i] - self.w_list[i][0] * x1 / self.w_list[i][1]
plt.plot(x1, y_axis)
plt.show()
def perdict(self,x):
y_perdict = np.sum(np.dot(self.w,x)) + self.b
if y_perdict > 0:
return 1
else:
return 0
|
c8f5a59148832b12a56f3008b75f256e4ceaf523 | kirihar2/coding-competition | /find_parallel.py | 1,559 | 3.96875 | 4 |
##Method 1: Create all rectangles and filter out ones that are not parallel to x
##Method 2: Find all lines parallel to x, then try to find the lines that have the same start and end x values
##Method 3: Find all y values with the same x. Like a bucket for each x value and their counts. set of 2 lines that have same y
# with each other is a rectangle parallel to x-axis
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def find_parallel(points):
x_bucket={}
for point in points:
if point[0] not in x_bucket:
x_bucket[point[0]] = {}
if point[1] not in x_bucket[point[0]]:
x_bucket[point[0]][point[1]] = 1
else:
x_bucket[point[0]][point[1]]+=1
x_bucket = [x_bucket[i] for i in x_bucket.keys()]
ret = 0
for i in range(len(x_bucket)):
curr_x = x_bucket[i]
for j in range(i+1,len(x_bucket)):
other_x = list(v for v in x_bucket[j])
number_lines_y = 0
for ind in range(len(other_x)):
y1 = other_x[ind]
if y1 in curr_x:
number_lines_y += 1
ret+= choose(number_lines_y,2)
return ret
points = [[10,20],[10,30],[20,30],[20,40],[20,20],[10,40],[10,50],[20,50]]
print(find_parallel(points)) |
04c99b844556b05ebeabfe3b85e4817c21513531 | dev1ender/learn | /largest-number.py | 480 | 3.9375 | 4 | from functools import cmp_to_key
def compare(a,b):
ab = str(a)+str(b)
ba= str(b)+str(a)
if ab < ba:
return 1
elif ab > ba:
return -1
else:
return 0
letter_cmp_key = cmp_to_key(compare)
def largestNumber(A):
A = sorted(A, key=letter_cmp_key)
result = ''
for item in A:
result+=str(item)
print(str(int(result)))
return str(int(result))
largestNumber([0, 0, 0, 0, 0])
|
40111d0d138bf968252e6dcd0a72b3dfdb714a8c | AlexanderRagnarsson/M | /Assignments/Assignment 9/Contentoffileinoneline.py | 134 | 3.59375 | 4 | read_file = open("test.txt")
for line in read_file:
for word in line:
print(word.strip(), end=(''))
read_file.close() |
6c97e6cae5c0bcc93a4dfc1cbae514fa5e0f76ec | tulsishankarreddy/repository_training | /python_program/day2/seq.py | 801 | 4.25 | 4 | List = [10, 20, 30]
#print with List value using negative indexes
if(0):
num = -len(List)
for i in range(-1,num-1,-1):
print(List[i])
#check we can change the or not tuple with in list
List1 = [10,20,(40,50)]
if(0):
print(List1[0])
print(List1[1])
print(List1[2])
print(List1[2][0])
print(List1[2][1])
List1[2] = (100,200)
print(List1)
''' List1[2][0] = 100 # we can't assign tuple to value '''
#check if it possible to change value of list in tuple
tuple1 = (10,20,[40,50])
if(0):
print(tuple1)
print(tuple1[2])
print(tuple1[2][0])
tuple1[2][0] = 100
print(tuple1)
''' tuple1[2] = [50,60] # we can't assign value to tuple '''
#slicing
List2 = [10,20,30,40,50]
if(1):
print(List2[1:4])
print(List2[:3])
print(List2[2:])
print(List2[:])
print(List2[1::2])
|
f3085db08bdcd025393c3930cb820b70f92f80bf | stupidchen/leetcode | /src/leetcode/P5367.py | 446 | 3.59375 | 4 | class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
for i in range(1, n):
if s[:n - i] == s[i:]:
return s[i:]
return ''
if __name__ == '__main__':
print(Solution().longestPrefix("aa"))
print(Solution().longestPrefix("level"))
print(Solution().longestPrefix("ababab"))
print(Solution().longestPrefix("leetcodeleet"))
print(Solution().longestPrefix("a"))
|
2784d54055d41c4bf29d05bebd22d48c76f715fb | vianneylotoy/TriRandom | /interval.py | 373 | 3.53125 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from random import randint,randrange
class Intervalle:
#Attribute of instances of the class
def __init__(self):
self.st = 0 # st: start time of the interval,
self.et = 0 # et: end time of the interval
self.Φ = 0 # Φ(t): Amount of energy in interval at t time
|
d645512387078f598f13e8bb1d6f849972378f41 | bgayathri/Learning-Python | /Python_programs/functions.py | 261 | 3.703125 | 4 | def computepay(h,r):
if h > 40:
gross_pay = r * 40 + ((r * 1.5) * (h - 40))
else:
gross_pay = h * r
return gross_pay
hrs = raw_input("Enter Hours:")
h = float(hrs)
rph = raw_input("Enter Rate:")
r = float(rph)
p = computepay(h,r)
print p |
6d3ee23c37b5bfc9c267eefefe1a75a872df55a9 | aaaaatoz/handdytools | /portchecker.py | 852 | 3.921875 | 4 | #!/usr/bin/python
import socket
def checkport(host,port):
''' this function tested if the host+port is avaiable
input:
host: host
port: tcp port
output: none. the boolean result successful or not
'''
result = False
try:
sock = socket.create_connection((host,port),timeout=5)
result = True
except socket.error as msg:
sock = None
finally:
if sock is not None:
sock.close()
return result
if __name__ == '__main__':
for hostinfo in open('hostport.conf','r'):
host,port,comment=hostinfo.strip().split()
result = checkport(host,int(port))
print "Port checking on %s,\t%s\tport %s is " %(host,comment,port) + str ( result)
|
9d0fc3aa90abcc5713a49a2fa7143430fe11748b | Yara7L/python_learn | /basic_2.py | 283 | 3.875 | 4 | import numpy as np
# shape的使用
def shape():
a = np.array([1, 2, 3, 4])
print(a.shape)
print(a)
b=a.reshape((2,2))
print(b)
print(b.shape)
c=a.reshape((1,-1))
print(c)
print(c.shape)
d=a.reshape((-1,1))
print(d)
print(d.shape) |
13613d9fa55d90f18555db6b817561ea35636795 | iPROGRAMMER007/Beginner | /AveOfFiveNum.py | 279 | 3.9375 | 4 | n1=float(input('Enter first number: '))
n2=float(input('Enter second number: '))
n3=float(input('Enter third number: '))
n4=float(input('Enter forth number: '))
n5=float(input('Enter fifth number: '))
ave=(n1+n2+n3+n4+n5)/5
print('Average of five numbers =',ave )
|
82929fc3ae5c9c3c77c4cd9192af5d6435baf8f0 | liuzhipeng17/python-common | /python基础/第三方模块/time时间模块/各种表示时间的相互转换.py | 1,041 | 3.65625 | 4 | # -*- coding: utf-8 -*-
import time
import calendar
# 时间戳---UTC struct time time.gmtime(时间戳)
print(time.gmtime(0))
print(time.gmtime()) #是在UTC时区,tm_hour可以看出相差8小时,中国的快了8小时
# 时间戳---Local struct time time.localtime(时间戳)
print(time.localtime()) # 宿主计算机所在地的时区
print(time.localtime(0))
#UTC struct time ---时间戳 calendar.timegm()
s = (1970, 1, 1, 0, 0, 0,3, 1, 0) #元组形式
print(calendar.timegm(s))
#当地时区struct time --->时间戳 time.mktime()
print(time.mktime(time.localtime()))
# struct time (tuple time)---字符串时间 time.strftime(format,t)
# struct time通常是由gmtime, localtime获得,通过格式化成字符串
# format是必要参数,t是可选参数,如果没有t,则默认t = time.localtime()
time_format = '%x' # 小写的x表示年月日date日期
local_tuple = time.localtime()
print(time.strftime(time_format, local_tuple))
# 字符串时间转成struct time time.strptime(time_str, time_format)
|
4ba3b59b00823d6cb170d2dd1ae18016b49a17d1 | 2020668/python2019 | /hm_04_面向对象特性/hm_14_练习.py | 324 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
=================================
@author: keen
Created on: 2019/4/25
E-mail:keen2020@outlook.com
=================================
"""
import random
class Base(object):
p = random.randint(1, 10)
class My(Base):
pass
class Pc(Base):
pass
my = My()
pc = Pc()
print(my.p)
print(pc.p)
|
8bb344287030e6594067fbd66cca6adb0814cd81 | VanessaSergeon/Python---Treehouse-Challenges | /most_classes.py | 620 | 3.96875 | 4 | # The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Often, it's a good idea to hold onto a max_count variable.
# Update it when you find a teacher with more classes than
# the current count. Better hold onto the teacher name somewher
# too!
#
# Your code goes below here.
def most_classes(dict):
most = 0
the_most = 'me'
for key in dict:
count = 0;
for value in dict[key]:
count = count + 1
if count > most:
most = count
the_most = key
print the_most |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.