blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
739deb3781688b27093a7e5236e93f31ea9d3abf | AnthonyDem/LeverX_tasks | /task1/LoadData.py | 297 | 3.53125 | 4 | import json
from abc import ABC, abstractmethod
class LoadDATA(ABC):
@abstractmethod
def load(self, filename):
pass
class LoadJSON(LoadDATA):
def load(self, filename):
with open(filename, 'r') as f:
json_data = json.load(f)
return json_data
|
3dbd30a5dab549c4130c9b46d17118f268028f0c | nickszap/mpas-tools | /python/memUtils.py | 772 | 3.796875 | 4 | #If we're working with big data, we may not be able to load all we want into memory.
#So, we need to be able to find how much space we have available
import os
import numpy as np
szFloat = 8 #size of a float in bytes (assume 64 bit)
def findRAM():
#return the RAM in bytes
txt = os.popen("free -m -b").readlines()
freeM = txt[1].split()[3] #pretty hacky but is there another option?
return int(freeM)
def calcNDecomp(nVals):
#return # of partitions needed to store all of these.
#we need to account for python's data structures needing space too.
fac = .8 #how much of free ram we can use. <1 but who knows how much...
totMem = int(fac*findRAM())
dataMem = nVals*szFloat #this is a lower bound!
return 1+dataMem/totMem #integer division
|
08e48ae76c18320e948ec941e0be4b598720feeb | nkarasovd/Python-projects | /Data Structures and Algorithms Specialization/Algorithms on Strings/week2/4_suffix_array/suffix_array.py | 632 | 4.1875 | 4 | # python3
import sys
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
suffixes = [(text[i:], i) for i in range(len(text))]
result_util = sorted(suffixes, key=lambda x: x[0])
result = [el[1] for el in result_util]
return result
if __name__ == '__main__':
text = sys.stdin.readline().strip()
print(" ".join(map(str, build_suffix_array(text))))
|
5011e91ffec203710c6c2dc1bc9e584bb13f21a8 | nkarasovd/Python-projects | /Data Structures and Algorithms Specialization/Algorithmic Toolbox/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.py | 613 | 3.859375 | 4 | # Uses python3
import sys
def get_fibonacci_huge_naive(n, m):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % m
def get_fibonacci_huge(n, m):
el_mod_m, i = [0, 1], 2
while not (el_mod_m[i - 2] == 0 and el_mod_m[i - 1] == 1) or i <= 2:
el_mod_m.append((el_mod_m[i - 2] + el_mod_m[i - 1]) % m)
i += 1
return el_mod_m[n % (i - 2)]
if __name__ == '__main__':
input = sys.stdin.read()
n, m = map(int, input.split())
print(get_fibonacci_huge(n, m))
|
fbbdd51ebf6d427735647f2906bc3ef7bf02eab7 | nkarasovd/Python-projects | /Data Structures and Algorithms Specialization/Data Structures/week2_priority_queues_and_disjoint_sets/2_job_queue/job_queue.py | 1,188 | 3.78125 | 4 | # python3
from collections import namedtuple
from queue import PriorityQueue
AssignedJob = namedtuple("AssignedJob", ["started_at", "worker"])
def assign_jobs_naive(n_workers, jobs):
# TODO: replace this code with a faster algorithm.
result = []
next_free_time = [0] * n_workers
for job in jobs:
next_worker = min(range(n_workers), key=lambda w: next_free_time[w])
result.append(AssignedJob(next_worker, next_free_time[next_worker]))
next_free_time[next_worker] += job
return result
def assign_jobs(n_workers, jobs):
result = []
q = PriorityQueue()
for i in range(n_workers):
q.put(AssignedJob(0, i))
for el in jobs:
next_item = q.get()
result.append(AssignedJob(next_item.started_at, next_item.worker))
q.put(AssignedJob(next_item.started_at + el, next_item.worker))
return result
def main():
n_workers, n_jobs = map(int, input().split())
jobs = list(map(int, input().split()))
assert len(jobs) == n_jobs
assigned_jobs = assign_jobs(n_workers, jobs)
for job in assigned_jobs:
print(job.worker, job.started_at)
if __name__ == "__main__":
main()
|
8ceb37c3de59ed9336a6e01e910269342fcee0cd | nkarasovd/Python-projects | /Data Structures and Algorithms Specialization/Algorithmic Toolbox/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py | 2,498 | 3.65625 | 4 | # Uses python3
import sys
import random
def less_than_or_equal(num1, num2, let1, let2):
return less_than(num1, num2, let1, let2) or \
equal(num1, num2, let1, let2)
def less_than(num1, num2, let1, let2):
return num1 < num2 or \
(num1 == num2 and let1 < let2)
def equal(num1, num2, let1, let2):
return num1 == num2 and let1 == let2
def fast_count_segments(starts, ends, points):
cnt = [0] * len(points)
LEFT = 1
POINT = 2
RIGHT = 3
starts_l = [LEFT] * len(starts)
ends_r = [RIGHT] * len(ends)
points_p = [POINT] * len(points)
pairs_number = starts + ends + points
pairs_letter = starts_l + ends_r + points_p
randomized_quick_sort(pairs_number, pairs_letter, 0, len(pairs_number) - 1)
count_left = 0
point_counts = {}
for p in points:
point_counts[p] = 0
for i in range(len(pairs_number)):
if pairs_letter[i] == LEFT:
count_left += 1
elif pairs_letter[i] == RIGHT:
count_left -= 1
elif pairs_letter[i] == POINT:
if point_counts[pairs_number[i]] == 0:
point_counts[pairs_number[i]] += count_left
for i in range(len(points)):
cnt[i] = point_counts[points[i]]
return cnt
def partition3(a, b, l, r):
x = a[l]
letx = b[l]
begin = l + 1
end = l
for i in range(l + 1, r + 1):
if less_than_or_equal(a[i], x, b[i], letx):
end += 1
a[i], a[end] = a[end], a[i]
b[i], b[end] = b[end], b[i]
if less_than(a[end], x, b[end], letx):
a[begin], a[end] = a[end], a[begin]
b[begin], b[end] = b[end], b[begin]
begin += 1
a[l], a[begin - 1] = a[begin - 1], a[l]
b[l], b[begin - 1] = b[begin - 1], b[l]
return [begin, end]
def randomized_quick_sort(a, b, l, r):
if l >= r:
return
k = random.randint(l, r)
a[l], a[k] = a[k], a[l]
b[l], b[k] = b[k], b[l]
# use partition3
[m1, m2] = partition3(a, b, l, r)
randomized_quick_sort(a, b, l, m1 - 1);
randomized_quick_sort(a, b, m2 + 1, r);
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
m = data[1]
starts = data[2:2 * n + 2:2]
ends = data[3:2 * n + 2:2]
points = data[2 * n + 2:]
# use fast_count_segments
cnt = fast_count_segments(starts, ends, points)
for x in cnt:
print(x, end=' ')
|
5ca0f7f38f1189c633f417608870822049c318cb | somsubhra999/nlpc2_ngrams | /ngram_toolkit.py | 3,033 | 3.578125 | 4 | import nltk
from nltk.corpus import stopwords
from nltk.util import ngrams
from nltk.probability import FreqDist
from string import punctuation
class Ngram:
def __init__(self, text):
"""
Initialize
:param text: The string based on which the Ngram instance is created
"""
self.stop_words = set(stopwords.words('english'))
self.text = text
tokens = [token.lower() for token in nltk.word_tokenize(text)]
self.tokens = self.raw_tokens = tokens
self.filter_tokens(stpwords=True, punct=True)
def filter_tokens(self, stpwords=False, punct=False):
"""
Filter out tokens which are stopwords or punctuation characters based on parameters
:param stpwords: Filter out stopwords if set to True
:param punct: Filter out punctuation characters if set to True
:return: Nothing
"""
self.tokens = self.raw_tokens
if stpwords:
self.tokens = [token for token in self.tokens if token not in self.stop_words]
if punct:
self.tokens = [token for token in self.tokens if token not in punctuation]
def get_ngrams(self, n):
"""
Get a list of n-grams for the tokens attribute
:param n: The value of n in n-gram. eg. n=2 means bi-gram
:return: List of n-grams
"""
return ngrams(self.tokens, n)
def get_fdist(self, n):
"""
Get the frequency distribution for every n-gram (for a particular value of n).
Uses instance method get_ngrams to get the ngrams
:param n: The value of n in n-gram. eg. n=2 means bi-gram
:return: The frequency distribution object
"""
if n == 1:
fd = FreqDist(self.tokens)
else:
fd = FreqDist(self.get_ngrams(n))
return fd
@staticmethod
def update_fdist(old_fdist, new_ngrams):
"""
Updates the frequency distribution object for a new list of n-grams.
Useful when generating a single fdist from a text stream like when reading a file line by line
:param old_fdist: The old frequency distribution object
:param new_ngrams: The new list of n-grams which need to be included in fdist calculation
:return: The new frequency distribution object
"""
new_fdist = old_fdist
for ng in new_ngrams:
new_fdist[ng] += 1
return new_fdist
@staticmethod
def filter_fdist(old_fdist, keyword):
"""
Filters the frequency distribution object and keeps only n-grams which include the provided keyword
:param old_fdist: The old frequency distribution object
:param keyword: The word which must be necessarily present in every n-gram in the fdist
:return: The new frequency distribution object after filtering
"""
new_fdist = FreqDist()
for ng in old_fdist:
if keyword in ng:
new_fdist[ng] = old_fdist[ng]
return new_fdist
|
9a4dd9d5ad2ee654593e653c0b48bfb237a8fdb8 | EvilPuddingLemon/LearingFluentPython | /S5/s5_3.py | 862 | 3.84375 | 4 | # 使用 lambda 表达式反转拼写,然后依此给单词列表排序
fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana']
print(sorted(fruits, key=lambda word: word[::-1]))
# 判断对象能否调用
print(abs, str, 13)
print([callable(obj) for obj in (abs, str, 13)])
# 调用 BingoCage 实例,从打乱的列表中取出一个元素
import random
class BingoCage:
def __init__(self, items):
self._items = list(items)
random.shuffle(self._items)
def pick(self):
try:
return self._items.pop()
except IndexError:
raise LookupError('pick from empty BingoCage')
def __call__(self):
return self.pick()
bingo = BingoCage(range(3))
print(bingo.pick())
print(bingo())
print(bingo())
try:
bingo()
except Exception as e:
print(e)
print(callable(bingo)) |
32d37ea6fb3788732a021ec60820420bb0d88a16 | EvilPuddingLemon/LearingFluentPython | /S2/s2_4.py | 897 | 3.734375 | 4 | l = [10, 20, 30, 40, 50, 60]
print(l[:2]) # 在下标2的地方分割
print(l[2:])
s = 'bicycle'
print(s[::3])
print(s[::-1])
print(s[::-2])
invoice = """
0.....6................................40........52...55........
1909 Pimoroni PiBrella $17.50 3 $52.50
1489 6mm Tactile Switch x20 $4.95 2 $9.90
1510 Panavise Jr. - PV-201 $28.00 1 $28.00
1601 PiTFT Mini Kit 320x240 $34.95 1 $34.95
"""
SKU = slice(0, 6)
DESCRIPTION = slice(6, 40)
UNIT_PRICE = slice(40, 52)
QUANTITY = slice(52, 55)
ITEM_TOTAL = slice(55, None)
line_items = invoice.split('\n')[2:]
for item in line_items:
print(item[SKU], item[UNIT_PRICE], item[DESCRIPTION])
#print(line_items)
l2 = list(range(10))
print(l2)
l2[2:5] = [20, 30]
print(l2)
del l2[5:7]
print(l2)
l2[3::2] = [11, 22]
print(l2)
l2[2:5] = [100]
print(l2)
|
5f15d80f5c1fc3231babdf72ac33808b64382f9d | EvilPuddingLemon/LearingFluentPython | /S14/s14_2.py | 461 | 3.96875 | 4 | s = 'ABC'
for char in s:
print(char)
it = iter(s)
while True:
try:
print(next(it))
except StopIteration:
del it # 释放对it的引用,废弃迭代器对象
break
from PythonTest.S14.s14_1 import Sentence
s3 = Sentence('Pig and Pepper')
it = iter(s3)
print(it)
print(next(it))
print(next(it))
print(next(it))
try:
print(next(it))
except StopIteration as e:
print(e)
print(list(it))
del it
print(list(iter(s3)))
|
eecf88de6663ff92751e5d351d896226172db8dc | EvilPuddingLemon/LearingFluentPython | /S8/s8_7.py | 459 | 4.03125 | 4 | import copy
t1 = (1, 2, 3)
t2 = tuple(t1)
print(t2 is t1) # t1 和 t2 绑定到同一个对象。
t3 = t1[:]
print(t3 is t1)
t4 = (1, 2, 3)
t5 = copy.deepcopy(t1)
print(t4 is t1)
# 在控制台上建立两个一样的元祖则会输出false,而执行这个则会输出True,可能是优化了不会新建副本
print(t5 is t1)
# 而使用深复制的无论是控制台和执行都没有新建副本,都是输出True
s1 = 'ABC'
s2 = 'ABC'
print(s1 is s2) |
69be93a66ceb167f035c82ff7464debde8b5623b | mvoin21/even | /hm13.py | 422 | 3.75 | 4 | number_list = input()
number_list = b.split(',')
d = []
for item in c:
if int(item) % 2 == 0:
d.append(item)
print(d)
#simple
c = [int(item) for item in d if int(item) % 2 == 0]
for item in d:
print(d)
#simple2
number_list = input()
number_list = number_list.split(',')
def number_is_even(number):
return int(number) % 2 == 0
for item in list(filter(number_is_even, number_list)):
print(item) |
78c35b9cff585e68786287f0260a61021f42614d | FilippoRanza/simpla | /utils/extract_regex.py | 982 | 3.671875 | 4 | #! /usr/bin/python
import re
match_regex = re.compile(r"match\s+\{")
else_regex = re.compile(r"\}\s+else\s+\{")
name_regex = re.compile(r"""(r"([^"]+)")""")
word = re.compile(r"[a-z]+")
stat = False
output = ""
with open('src/simpla.lalrpop') as file:
for line in file.readlines():
if match_regex.match(line):
stat = True
elif else_regex.match(line):
stat = False
if stat:
line = line.strip()
if match := name_regex.match(line):
regex = match[1]
name = match[2]
if word.match(name):
terminal_name = name.capitalize() + "KW"
else:
terminal_name = input(f"Name for {regex} ")
terminal_name += "Punct"
line = f"{terminal_name} = <{regex}>;\n"
output += line
with open('terminals.txt', "w") as file:
print(output, file=file)
|
f9f3e4c6fa9efe25bbe23a3ccdfbf92080670da6 | BriskyGates/Study-Plan | /大神的资料库/4. 排序算法 - Sorting/2. 选择排序 - Selection Sort/2_select_sort_desc.py | 971 | 3.90625 | 4 | def selection_sort(L):
'''选择排序,降序'''
n = len(L)
if n <= 1:
return
for i in range(n-1): # 共需要n-1次选择操作
max_index = i # 首先假设 "未排序列表"(上图中非绿色框) 的最大元素是它的第1个元素,第1次选择操作则假设L[0]是最大的,第2次操作则假设L[1]是最大的
for j in range(i+1, n): # 找出 "未排序列表" 中真正的最大元素的下标
if L[j] > L[max_index]:
max_index = j
if max_index != i: # 如果 "未排序列表" 中真正的最大元素,不是之前假设的元素,则进行交换
L[i], L[max_index] = L[max_index], L[i]
if __name__ == '__main__':
L1 = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('Before: ', L1)
selection_sort(L1)
print('After: ', L1)
# Output:
# Before: [54, 26, 93, 17, 77, 31, 44, 55, 20]
# After: [93, 77, 55, 54, 44, 31, 26, 20, 17]
|
9b4d606eef01315c9eb090f0ac4ca713411b7883 | BriskyGates/Study-Plan | /basic training/handle pdf page/handle_continue_page.py | 929 | 3.59375 | 4 | # 专门用来处理分页
from utils.single_link import SingleLinkedList
data = [ 4, 5, 6]
data=[2, 4, 5, 8]
# b = [[2, 2], [4, 5], [8, 8]]
# data = [1, 4, 5, 6, 8]
# c = [[1, 1], [4, 6], [8, 8]]
final_result = []
index = 0
while index < len(data):
sing = None
if index == len(data) - 1:
final_result.append(SingleLinkedList(data[index]))
elif data[index] + 1 == data[index + 1]:
flag = False
index_begin = index
while True:
index += 1
index_end = index
if data[index] + 1 == data[index + 1]:
index_end = index
else:
break
sing = SingleLinkedList()
for continual_ele in data[index_begin:index_end + 1]:
sing.append(continual_ele)
final_result.append(sing)
else:
sing = SingleLinkedList(data[index])
final_result.append(sing)
index += 1
pass
|
cef0062535c22608607714f231b4bb185bf5fa9f | BriskyGates/Study-Plan | /菜鸡的日常训练/数据结构/并查集.py | 2,381 | 3.515625 | 4 | class UniorFind:
def __init__(self):
"""记录每个节点的父节点"""
self.father = [] # 大列表中套着小字典,键为子节点,值为父节点
# 添加新节点到并查集,他的父节点为空
def add(self, x):
if x not in self.father:
self.father[x] = None
def merge(self, x, y):
"""
如果发现两个节点是连通的,那么就要合并它们<祖先是相同的>,究竟把谁当做父节点是不在乎的
Args:
x:
y:
Returns:
"""
root_x, root_y = self.find(x), self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
# 也可以写成 self.father[root_y] = root_x
def is_connected(self, x, y):
"""
查看两个节点是否为连通,判断父节点是否一致,当然也可以看看他们的祖先<父节点的父节点>是否一致
Args:
x:
y:
Returns:
"""
return self.find(x) == self.find(y)
def find(self, x):
"""
实现原理: 不断往上遍历, 查询到根节点
SHORTCOMING:
if 树的深度比较大, 比如退化成链表,那么每次查询的效率比较低
IMP 原因:并查集只是记录节点间的连通关系,而节点相互连通只需要有一个相同的祖先即可
Args:
x:
Returns:
"""
root = x # 刚开始将当前节点默认为是父节点
while self.father[root] is not None: # 利用只有根节点的父节点才为None
root = self.father[root]
return root
def find2(self, x):
"""
路径压缩,降低树的深度,例如固定成2
Args:
x:
Returns:
"""
root = x
# 循环1
while self.father[root] is not None: # 不断往上遍历,找到根节点
root = self.father[root]
# 路径压缩
while x != root: # 当前节点不是根节点
original_father = self.father[x] # x的父节点赋值给original_father
self.father[x] = root # 将x的父节点变成经过循环1查询到的根节点
x = original_father # 将当前向上遍历的节点付给x, 便于检查original_father是否为祖先
return root
|
a9221172e4fa7c4eaed8d584e599f69bb6229b7b | BriskyGates/Study-Plan | /大神的资料库/2. 数据结构 - Data Structures/4. 树 - Tree/2. 二叉树 - Binary Tree/1_binary_tree.py | 6,696 | 3.796875 | 4 | class Node:
def __init__(self, data):
self.data = data # 节点的数据域
self.lchild = None # 节点的左孩子
self.rchild = None # 节点的右孩子
def __repr__(self):
return 'Node({!r})'.format(self.data)
class BinaryTree:
def __init__(self, root=None):
self.root = root
def add(self, data):
'''添加节点:广度优先,使用队列实现(这种方式是创建了 "完全二叉树",如果想创建普通二叉树就不行)'''
node = Node(data)
# 如果树还是空树,则把该节点添加为根节点
if self.root is None:
self.root = node
else:
queue = [] # 模拟队列
queue.append(self.root) # 首先把根节点加入队列
while queue:
cur = queue.pop(0) # 弹出队列中的第1个元素(即最先加入队列的元素,先进先出)
if cur.lchild is None:
cur.lchild = node
return
else:
# 如果弹出的节点的左孩子不为空,则把它的左孩子加入队列,后面继续判断左孩子
queue.append(cur.lchild)
if cur.rchild is None:
cur.rchild = node
return
else:
# 如果弹出的节点的右孩子不为空,则把它的右孩子加入队列,后面继续判断右孩子
queue.append(cur.rchild)
def breadth_first_search(self):
'''树遍历:广度优先,使用队列实现'''
if self.root is None:
return
queue = [] # 模拟队列
queue.append(self.root) # 首先把根节点加入队列
while queue:
cur = queue.pop(0) # 弹出队列中的第1个元素(即最先加入队列的元素,先进先出)
print(cur, end=' ') # 打印当前节点,注意,不换行
if cur.lchild is not None:
queue.append(cur.lchild)
if cur.rchild is not None:
queue.append(cur.rchild)
def breadth_first_search2(self):
'''树遍历:广度优先,使用队列实现
按层输出树的节点,即输出一层的节点后,换行,再输出下一层的节点:
Node(0)
Node(1) Node(2)
Node(3) Node(4) Node(5) Node(6)
Node(7) Node(8) Node(9)
如何实现:
last: 表示正在打印的当前行的最右孩子
nlast: 表示下一行的最右孩子
nlast 一直跟踪记录 '最新' 加入队列的节点即可,因为 '最新' 加入队列的节点一定是目前发现的下一层的最右孩子
'''
if self.root is None:
return
queue = [] # 模拟队列
last = self.root # 开始时,让 last 指向根节点
queue.append(self.root) # 首先把根节点加入队列
while queue:
cur = queue.pop(0) # 弹出队列中的第1个元素(即最先加入队列的元素,先进先出)
print(cur, end=' ') # 打印当前节点,注意,不换行
if cur.lchild is not None:
queue.append(cur.lchild)
nlast = cur.lchild # 加入左孩子时,让 nlast 指向左孩子
if cur.rchild is not None:
queue.append(cur.rchild)
nlast = cur.rchild # 加入右孩子时,让 nlast 指向右孩子
if last == cur: # 如果 last 与当前弹出的节点相同时,说明该换行了
last = nlast
print('') # 打印换行
def pre_order_traversal(self, cur):
'''树的遍历:深度优先,使用递归实现
前序遍历: 根、左、右
'''
if cur is None: # 递归的终止条件
return
print(cur, end=' ')
self.pre_order_traversal(cur.lchild) # 如果当前节点(叶子节点)没有左孩子,则传入的是None,会终止递归
self.pre_order_traversal(cur.rchild)
def in_order_traversal(self, cur):
'''树的遍历:深度优先,使用递归实现
中序遍历: 左、根、右
'''
if cur is None: # 递归的终止条件
return
self.in_order_traversal(cur.lchild) # 如果当前节点(叶子节点)没有左孩子,则传入的是None,会终止递归
print(cur, end=' ')
self.in_order_traversal(cur.rchild)
def post_order_traversal(self, cur):
'''树的遍历:深度优先,使用递归实现
后序遍历: 左、右、根
'''
if cur is None: # 递归的终止条件
return
self.post_order_traversal(cur.lchild) # 如果当前节点(叶子节点)没有左孩子,则传入的是None,会终止递归
self.post_order_traversal(cur.rchild)
print(cur, end=' ')
if __name__ == '__main__':
binary_tree = BinaryTree() # 创建空树
binary_tree.add(0) # 添加根节点
binary_tree.add(1)
binary_tree.add(2)
binary_tree.add(3)
binary_tree.add(4)
binary_tree.add(5)
binary_tree.add(6)
binary_tree.add(7)
binary_tree.add(8)
binary_tree.add(9)
print('*' * 20 + ' 广度优先: ' + '*' * 20)
binary_tree.breadth_first_search()
print('') # 换行
print('*' * 20 + ' 广度优先(按层打印): ' + '*' * 20)
binary_tree.breadth_first_search2()
print('*' * 20 + ' 前序遍历: ' + '*' * 20)
binary_tree.pre_order_traversal(binary_tree.root)
print('') # 换行
print('*' * 20 + ' 中序遍历: ' + '*' * 20)
binary_tree.in_order_traversal(binary_tree.root)
print('') # 换行
print('*' * 20 + ' 后序遍历: ' + '*' * 20)
binary_tree.post_order_traversal(binary_tree.root)
# Output:
# ******************** 广度优先: ********************
# Node(0) Node(1) Node(2) Node(3) Node(4) Node(5) Node(6) Node(7) Node(8) Node(9)
# ******************** 广度优先(按层打印): ********************
# Node(0)
# Node(1) Node(2)
# Node(3) Node(4) Node(5) Node(6)
# Node(7) Node(8) Node(9)
# ******************** 前序遍历: ********************
# Node(0) Node(1) Node(3) Node(7) Node(8) Node(4) Node(9) Node(2) Node(5) Node(6)
# ******************** 中序遍历: ********************
# Node(7) Node(3) Node(8) Node(1) Node(9) Node(4) Node(0) Node(5) Node(2) Node(6)
# ******************** 后序遍历: ********************
# Node(7) Node(8) Node(3) Node(9) Node(4) Node(1) Node(5) Node(6) Node(2) Node(0)
|
5cde3fa9958b34cfc915cf3d735e77b263102abf | mesikkera/DailyCoding | /Codility Lesson/BinaryGap.py | 2,246 | 3.90625 | 4 | """
BinaryGap
Find longest sequence of zeros in binary representation of an integer.
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded
by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2.
The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3.
The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
Write a function:
def solution(N)
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
Assume that:
N is an integer within the range [1..2,147,483,647].
Complexity:
expected worst-case time complexity is O(log(N));
expected worst-case space complexity is O(1).
Copyright 2009–2016 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
"""
# -*- coding: utf-8 -*-
# 가나다라
import time
# 정수 N --> 2진수
# 가장 긴 0의 연속 개수
def solution(N):
binary_number = bin(N)
max_gap = 0
current_gap = 0
max_sequence = 0
for digit in binary_number[2:]:
if digit == '0':
current_gap += 1
elif digit == '1':
max_gap = max(max_gap, current_gap)
current_gap = 0
return max_gap
def solution2(N):
pass
def main():
start_time = time.time()
result = solution(1041)
elapsed_time = time.time() - start_time
print("Result(1041): ", result)
print("Elapsed Time using solution1(1041): ", elapsed_time)
start_time = time.time()
result = solution(1376796946)
elapsed_time = time.time() - start_time
print("Result(1376796946): ", result)
print("Elapsed Time using solution1(1376796946): ", elapsed_time)
if __name__ == '__main__':
main()
|
711a67aac7b71d08042b2270c1ed22617f045591 | hvpeteet/Movement-Through-The-Void | /Movement Through The Void/Code/A New Start/CorrectGravity11-15-12.py | 4,115 | 3.640625 | 4 | from __future__ import division
from visual import*
from math import*
from visual.graph import *
## MKS units
##Solar Mass in Kilograms
SolarMass = 1.9891 * (10 ** 30)
EarthMass = 5.97219 * (10 ** 24)
SunEarthDist = 149597870700
G = 6.673 * (10 ** -11)
##List of all bodies entered, automatically appended
SystemOfBodies = []
class Body(object):
def __init__(self, velocity = vector(0, 0, 0), mass = 0, position = vector(0, 0, 0), identity = "unknown", radius = 0):
self.velocity = velocity
self.mass = mass
self.position = position
self.identity = identity
self.radius = radius
self.volume = (4/3) * pi * self.radius ** 3
self.density = self.mass / self.volume
SystemOfBodies.append(self)
def __str__(self):
return self.identity
def Gravity (Body1,Body2):
m1,m2 = Body1.mass, Body2.mass
dist = Body2.position-Body1.position
UnitForceVector = dist/mag(dist)
force = (G*m1*m2)/(mag(dist)**2)*UnitForceVector
## print force
return force
def SystemGravity(system, timestep):
"""changes the position of the bodies in system in time 'time' as one step, the smaller the step the better the outcome"""
for body1 in system:
for body2 in system:
if body1 != body2:
## print body1.velocity
ac = (Gravity(body1,body2)/body1.mass)
## print ac
body1.velocity = body1.velocity + ac*timestep
## print ac,ac*timestep
a = body1.position
body1.position = body1.position + body1.velocity*timestep
## print body1.velocity*timestep,
## print a-body1.position
## print body1,body1.position
def OrbitVelocity(Body1,Body2):
dist = Body2.position-Body1.position
UnitTangentVector = vector(dist.y, -dist.x, 0)/mag(dist)
print mag(UnitTangentVector)
Body1.velocity = UnitTangentVector*sqrt((Body2.mass*G)/mag(Body1.position-Body2.position))
print Body1.velocity
##Test Harness
x = Body(velocity = vector(0,0,0), mass = SolarMass, position = vector(0, 0, 0),identity = "sun", radius = SunEarthDist/2)
y = Body(velocity = vector(0,0,0), mass = EarthMass, position = vector(SunEarthDist,0,0), identity = "earth", radius = SunEarthDist/8)
##z = Body(velocity = vector(0,-2,-10), mass = 1, position = vector(5,0,0), identity = "mars", radius = .5)
OrbitVelocity(y,x)
##Gravity(x,y)
sys2 = [x,y]
##SystemGravity(sys2,.1)
##
##SystemRun(sys2,1,1000000000000)
##def RunSystem(system, timestep, time):
## VisualSystem = []
## for body in range (len(system)):
## visual = sphere(pos = system[body].position, radius = system[body].radius)
## visual.trail = curve(color = color.blue)
## VisualSystem.append(visual)
##
## for frame in range(int(time/timestep)):
## rate (10)
## system[1].position = frame*10**20
#### SystemGravity(system, timestep)
def SystemRun(system, timestep, time):
VisualSystem = []
for body in range (len(system)):
print system[body]
Visual = sphere(pos = system[body].position, radius = system[body].radius)
Visual.trail = curve(color = color.blue)
VisualSystem.append (Visual)
print len(VisualSystem)
frame = 0
final_frame = time / timestep
while frame < final_frame:
rate(15)
SystemGravity(system, timestep)
for body in range(len(system)):
VisualSystem[body].pos = system[body].position
VisualSystem[body].trail.append(pos = VisualSystem[body].pos)
##Need to change when mases are made realistic format - 1st num = 0 so we are in the red spectrum
## second and third in between 0 and 1
## second, the closer to 0, the brighter
## third the closer to 0 the closer to black
## VisualSystem[body].color = color.hsv_to_rgb((0, system[body].mass / (3 * SolarMass), system[body].density / 10))
frame += 1
print "done"
SystemRun(sys2, 60*60*24, 60*60*24*365)
|
efc9ede3541d2df46533414e7f00d9343f22bab0 | hvpeteet/Movement-Through-The-Void | /Movement Through The Void/Code/A New Start/BodiesClassSafeSave11.10.12.py | 1,618 | 3.90625 | 4 | from visual import*
from math import*
SystemOfBodies = []
class Body(object):
def __init__(self, velocity = vector(0,0,0), mass = 0, position = vector(0,0,0), identity = "unknown"):
self.velocity = velocity
self.mass = mass
self.position = position
self.identity = identity
SystemOfBodies.append(self)
def __str__(self):
return self.identity
def GetSystem():
"""returns a list of all bodies created in the system"""
return SystemOfBodies
def GravityToAccel(Body1,Body2):
"""returns the acceleration due to gravity between two bodies"""
G = 1
dist = (Body2.position-Body1.position)
force = (G*Body1.mass*Body2.mass) / (mag(dist)**2)
accel1 = dist*(force/Body1.mass)
accel2 = dist*(force/Body2.mass)
return accel1,accel2
def SystemGravity(system, time):
"""changes the position of the bodies in system in time 'time' as one step, the smaller the step the better the outcome"""
NewSystem = system
print "new"
for Body1 in range(len(NewSystem)):
## print Body1
for Body2 in range(len(NewSystem) - (Body1+1)):
Body2 = len(NewSystem) - (Body2+1)
## print Body2
print NewSystem[Body1],NewSystem[Body2]
##Test Harness
x = Body(vector(1,1,1), mass = 12, position = vector(1,1,1),identity = "earth")
y = Body(vector(0,0,0), mass = 6, position = vector(-1,-1,-1), identity = "moon")
##print GetSystem()
print GravityToAccel(x,y)
sys1 = [1,2,3,4,5,6,7,8,9,10]
sys2 = [x,y]
SystemGravity(sys1,5)
SystemGravity(sys2,5)
|
3df884385b800ccf0a32ce18e5fdbaee7b4c9bf9 | hvpeteet/Movement-Through-The-Void | /Movement Through The Void/Code/A New Start/BodiesClassSafe11.12.12 | 3,326 | 3.875 | 4 | from visual import*
from math import*
SystemOfBodies = []
class Body(object):
def __init__(self, velocity = vector(0,0,0), mass = 0, position = vector(0,0,0), identity = "unknown"):
self.velocity = velocity
self.mass = mass
self.position = position
self.identity = identity
SystemOfBodies.append(self)
def __str__(self):
return self.identity
def GetSystem():
"""returns a list of all bodies created in the system"""
return SystemOfBodies
def GravityToAccel(Body1,Body2):
"""(Body, Body) -> vector, vector
Returns the acceleration due to gravity between two bodies
"""
G = 6.673 * (10**-11)
dist = (Body2.position-Body1.position)
force = (G*Body1.mass*Body2.mass) / (mag(dist)**2)
accel1 = dist*(force/Body1.mass)
accel2 = -dist*(force/Body2.mass)
return accel1,accel2
def SystemGravity(system, time):
"""changes the position of the bodies in system in time 'time' as one step, the smaller the step the better the outcome"""
for Body1 in range(len(system)):
for Body2 in range(len(system) - (Body1+1)):
Body2 = len(system) - (Body2+1)
ac1,ac2 = GravityToAccel(system[Body1],system[Body2])
system[Body1].velocity += ac1*time
system[Body2].velocity += ac2*time
system[Body1].position += system[Body1].velocity*time
system[Body2].position += system[Body2].velocity*time
## print system[Body1], system[Body1].position,system[Body2],system[Body2].position
def SystemRun(system, timestep, time):
VisualSystem = []
for body in range ( len (system) ):
print system[body]
Visual = sphere(pos = system[body].position, radius = 10**12)
Visual.trail = curve(color = color.blue)
VisualSystem.append (Visual)
print len(VisualSystem)
frame = 0
final_frame = time/timestep
while frame < final_frame:
rate(1)
SystemGravity(system, timestep)
for body in range ( len(system)):
VisualSystem[body].pos = system[body].position
VisualSystem[body].trail.append(pos = VisualSystem[body].pos)
frame += 1
print "done"
##Test Harness
x = Body(velocity = vector(0,0,0), mass = 1.9891*(10**30), position = vector(0, 0, 0),identity = "sun")
y = Body(velocity = vector(0,107300000,0), mass = 5.97219*(10**24), position = vector(150*(10**6),0,0), identity = "earth")
z = Body(velocity = vector(0,-11245,1), mass = 6.41693*(10**23), position = vector(-206669*(10**6),0,0), identity = "mars")
##print GetSystem()
##print GravityToAccel(x,y)
sys1 = [1,2,3,4,5,6,7,8,9,10]
sys2 = [x,y,z]
##SystemGravity(sys1,5)
SystemRun(sys2,1,100)
##SystemGravity(sys2,0)
##SystemGravity(sys2,1)
##SystemGravity(sys2,0)
##SystemGravity(sys2,1)
##x = sphere(pos = x.position, radius = .25, color = color.blue)
##y = sphere(pos = y.position, radius = .125, color = color.white)
##t = 0
##r = vector(0, 0, 0)
##y.trail = curve(color = color.blue)
##while t < 100:
## rate(7)
## r = (sin(t), cos(t), sin(t))
## y.pos = r
## y.trail.append(pos = y.pos)
## t = t + .1
##while t < 100:
## rate(7)
## r = (sin(t), cos(t), sin(t))
## y.pos = r
## y.trail.append(pos = y.pos)
## t = t + .1
|
67a127a5d4b5a8d87349bcfce91aacc3586bb845 | littleocub/python_practice | /bj_tmp_matplotlib/beijing_2016.py | 1,722 | 3.609375 | 4 | # beijing_2016
import csv
import matplotlib.dates
from datetime import datetime
from matplotlib import pyplot as plt
def date_to_list(data_index):
""" save date to a list """
results = []
for row in data:
results.append(datetime.strptime(row[data_index], '%Y-%m-%d'))
return results
def data_to_list(data_index):
""" save data to a list """
results = []
for row in data:
results.append(int(row[data_index]))
return results
filename = 'beijing_2016.csv'
with open(filename) as bj:
data = csv.reader(bj)
header = next(data)
# print(header)
# print(next(data))
# get the index of data needed
print('date_akdt', header.index('date_akdt'))
print('high_temp_f', header.index('high_temp_f'))
print('low_temp_f', header.index('low_temp_f'))
# create a list from the remaining contents in the iterable
data = list(data)
# save data to list
high_temp_f_bj = data_to_list(1)
high_temp_c_bj = [int((x-32)/1.8) for x in high_temp_f_bj]
low_temp_f_bj = data_to_list(3)
low_temp_c_bj = [int((x-32)/1.8) for x in low_temp_f_bj]
date = date_to_list(0)
plt.figure(figsize=(12, 5), dpi=100)
plt.plot(date, high_temp_c_bj, c='xkcd:orange')
plt.plot(date, low_temp_c_bj,c='xkcd:azure')
plt.title('Beijing Temperatures (High & Low) - Year 2016', fontsize=22)
plt.ylabel('Temperature (C)', fontsize=20)
plt.tick_params(axis='both', labelsize=16)
plt.fill_between(date, high_temp_c_bj, low_temp_c_bj, facecolor='xkcd:silver', alpha=0.2)
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m"))
plt.gcf().autofmt_xdate()
plt.margins(x=0,y=0.2)
plt.show() |
4d916dc9ff4fc56ec946f70a30d64cefc1a8dfda | tpatel84/LeetCode-Python | /valid_parentheses.py | 1,386 | 3.75 | 4 | class Solution:
def isValid(self, s: str) -> bool:
# main idea:
# A Last-In-First-Out (LIFO) data structure
# such as 'stack' is the perfect fit
if len(s)==0:
return True
valid_char = ['(', ')', '{', '}', '[', ']']
left_half = ['(', '[', '{']
right_half = [')', ']', '}']
# use a map/dictionary, which is more maintainable
another_half = {')': '(', '}':'{', ']':'['}
my_stack = []
for char in s:
if char not in valid_char:
return False
# we see an opening parenthesis, we push it onto the stack
if char in left_half:
my_stack.append(char)
# we encounter a closing parenthesis, we pop the last inserted opening parenthesis
if char in right_half:
if len(my_stack) == 0:
return False
# be careful: check if the pair is a valid match
elif another_half[char] != my_stack[len(my_stack)-1]:
return False
else:
my_stack.pop()
if len(my_stack) !=0:
return False
else:
return True
|
4700a7171b24baaff2510ed26a9848168434eff4 | tpatel84/LeetCode-Python | /validate_binary_search_tree.py | 990 | 4.09375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# define a method to test if it is a BST
def BST_valid(root, min_value, max_value):
# not a TreeNode
if not root:
return True
# the cases: not a BST
if (root.val >= max_value) or (root.val <= min_value):
return False
# test the left node
left_test = BST_valid( root.left, min_value, root.val)
# test the right node
right_test = BST_valid( root.right, root.val, max_value)
# return the result
return (left_test and right_test)
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# initialize the max and min values
max_inf = float('inf')
min_inf = float('-inf')
# recursive test
return BST_valid(root, min_inf, max_inf)
|
55da659894602b33b52575e848d2c360f9b58a90 | tpatel84/LeetCode-Python | /merge_two_sorted_lists.py | 1,422 | 4.03125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# the edge case(s):
if l1 == None:
return l2
if l2 == None:
return l1
# we insert a 'dummy head' before the new list
dummy_node = ListNode(None)
# new linked list
current_pointer= dummy_node
# current_pointer -> dummy_node
while (l1 != None) and (l2 != None):
# case 1
if l1.val <= l2.val:
current_pointer.next = l1
l1 = l1.next
current_pointer = current_pointer.next
# current_pointer.next -> l1
# l1 -> l1.next
# current_pointer -> l1
# case 2
else:
current_pointer.next = l2
l2 = l2.next
current_pointer = current_pointer.next
# current_pointer.next -> l2
# l2 -> l2.next
# current_pointer -> l2
if l1 == None:
current_pointer.next = l2
if l2 == None:
current_pointer.next = l1
return dummy_node.next
|
47b588ea32578dc637c67284d8be7cb15b466a83 | tpatel84/LeetCode-Python | /evaluate_reverse_polish_notation.py | 1,556 | 3.65625 | 4 | class Solution:
def evalRPN(self, tokens: List[str]) -> int:
# main idea:
# The Reverse Polish Notation (RPN) is also known as
# the 'postfix' notation, because each operator appears after its operands.
# Stack fits perfectly as it is a Last-In-First-Out (LIFO) data structure.
my_stack = []
operators = ['+', '-', '*', '/']
for token in tokens:
if token not in operators:
operand = int(token) # we need to change it to 'integer'
my_stack.append(operand) # push
else:
a = my_stack.pop()
b = my_stack.pop()
# be careful: need to use 'b-a' and 'b//a'
if token == '+':
c = b + a
my_stack.append(c)
elif token == '-':
c = b - a
my_stack.append(c)
elif token == '*':
c = b * a
my_stack.append(c)
else:
# special case (becasue Python is different from C language)
if b * a < 0:
c = -((-b) // a)
my_stack.append(c)
else:
c = b // a
my_stack.append(c)
final_value = my_stack.pop() # pop the final value in the stack
return final_value
|
306d2fbf187ed9dadc85d4b0c4cb28e2165225df | robertsj/ME701_examples | /gui/feval_1.py | 1,314 | 3.953125 | 4 | import sys
import numpy as np
from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QVBoxLayout
class Form(QLabel) :
def __init__(self, parent=None) :
super(Form, self).__init__(parent)
# Define three text boxes, one each for f(x), the value x, and
# the output. I've done the first for you.
self.function_edit = QLineEdit("f(x) = ...")
self.function_edit.selectAll() # What does selectAll() do?
# Step 1. Add box for "x"
# Step 2. Add box for "output"
# Step 3. How do we combine these widgets? Use a *layout*....
# Step 4. Make sure the function box is the default one active.
# Step 5. Connect updateUI to the event that one returns while the
# output box is active
# Step 6. Implement updateUI.
# Step 7. Give the GUI a title.
def updateUI(self) :
""" Method for updating the user interface.
This is called whenever an event triggers an update. Specifically,
this event is when the return key is pressed when the output box
is active. The result of this method should be to show the
resulting function value (f of x) in the output box."""
pass
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
|
7131a0c430d7abb53d9486e1f81398e5c9f4b475 | ljcopsey/dicegame | /dicegame_algo.py | 4,973 | 3.625 | 4 | import itertools
from dice_game import DiceGame
game = DiceGame()
import numpy as np
from abc import ABC, abstractmethod
class DiceGameAgent(ABC):
def __init__(self, game):
self.game = game
@abstractmethod
def play(self, state):
pass
class AlwaysHoldAgent(DiceGameAgent):
def play(self, state):
return (0, 1, 2)
class PerfectionistAgent(DiceGameAgent):
def play(self, state):
if state == (1, 1, 1) or state == (1, 1, 6):
return (0, 1, 2)
else:
return ()
def play_game_with_agent(agent, game, verbose=True):
state = game.reset()
if(verbose): print(f"Testing agent: \n\t{type(agent).__name__}")
if(verbose): print(f"Starting dice: \n\t{state}\n")
game_over = False
actions = 0
while not game_over:
action = agent.play(state)
actions += 1
if(verbose): print(f"Action {actions}: \t{action}")
_, state, game_over = game.roll(action)
if(verbose and not game_over): print(f"Dice: \t\t{state}")
if(verbose): print(f"\nFinal dice: {state}, score: {game.score}")
return game.score
if __name__ == "__main__":
# random seed makes the results deterministic
# change the number to see different results
# or delete the line to make it change each time it is run
np.random.seed(1)
game = DiceGame()
# agent1 = AlwaysHoldAgent(game)
#play_game_with_agent(agent1, game, verbose=True)
print("\n")
#agent2 = PerfectionistAgent(game)
#play_game_with_agent(agent2, game, verbose=True)
class MyAgent(DiceGameAgent):
def __init__(self, game):
"""
if your code does any pre-processing on the game, you can do it here
e.g. you could do the value iteration algorithm here once, store the policy,
and then use it in the play method
you can always access the game with self.game
"""
# this calls the superclass constructor (does self.game = game)
super().__init__(game)
# YOUR CODE HERE
self.gamma = 0.9
self.theta = 0.1
def play(self, state):
"""
given a state, return the chosen action for this state
at minimum you must support the basic rules: three six-sided fair dice
if you want to support more rules, use the values inside self.game, e.g.
the input state will be one of self.game.states
you must return one of self.game.actions
read the code in dicegame.py to learn more
"""
# YOUR CODE HERE
v = self.val_iteration()
policy = self.find_best_actions(v)
return policy
def utility_dictionary(self):
util = {}
for s in game.states:
util[s] = 0
return util
def max_action(self, state, util):
maximum = 0
for a in game.actions:
next_states, _, reward, probabilities = game.get_next_states(a, state)
temp = 0
for next_state, prob in zip(next_states, probabilities):
if next_state is None:
u = 0
else:
u = util[next_state]
temp = temp + prob * (reward + self.gamma * u)
if temp > maximum:
maximum = temp
return maximum, a
def val_iteration(self):
v = self.utility_dictionary()
while True:
delta = 0
for s in game.states:
temp = v[s]
v[s], _ = self.max_action(s, v)
delta = max(delta, np.abs(temp - v[s]))
if delta < self.theta:
break
return v
def find_best_actions(self, v):
policy = {}
# for each state in the dictionary, find the best action
for s in v:
_, policy[s] = self.max_action(s, v)
best_action = max(policy.values())
return best_action
#TESTING
import time
total_score = 0
total_time = 0
n = 10
np.random.seed()
print("Testing basic rules.")
print()
game = DiceGame()
start_time = time.process_time()
test_agent = MyAgent(game)
total_time += time.process_time() - start_time
for i in range(n):
start_time = time.process_time()
score = play_game_with_agent(test_agent, game)
total_time += time.process_time() - start_time
print(f"Game {i} score: {score}")
total_score += score
print()
print(f"Average score: {total_score/n}")
print(f"Total time: {total_time:.4f} seconds") |
458f9df863f6be3238eb0429c06861f02407c942 | madamczak/ZamenaKurs | /dzien4requests/zadaniarequests_daniel.py | 4,240 | 3.59375 | 4 | #napisz funkcję która jako argument przyjmie stringa url, sprawdzi czy string rozpoczyna się od http:// lub https://
#następnie wykona request typu get, sprawdzi czy kod odpowiedzi zaczyna się na 2(OK) lub 3(Przekierowanie)
#i dalej już tylko utworzy obiekt BeautifulSoup, jako argumenty do budowy obiektu podasz tekst strony a jako parser "lxml"
#i na końcu zwróci go z funkcji
#w każdym kroku sprawdzającym możesz uznać że jeżeli warunek nie jest spełniony to możesz od razu ją przerwać i zwrócić obiekt None
print('Zad. 1.')
import requests
agent = {
"User-Agent": 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
}
from bs4 import BeautifulSoup
def url_validator(url):
if not (url.startswith("http://") or url.startswith("https://")):
return "Incorrect url."
url_get = requests.get(url, headers=agent)
response_code = str(url_get.status_code)
if not (response_code.startswith("2") or response_code.startswith("3")):
return "Error response code (" + response_code + ")."
soup = BeautifulSoup(url_get.text, "lxml")
return soup
#jak przetesowałbyś tą funkcje? Co tu może pójść nie tak z tym testowaniem? Jak ją nazwałeś?
print(url_validator("htps://redeem.backtoblackvinyl.com/psy/pies.html"))
print(url_validator("https://redeem.backtoblackvinyl.com/psy/pies.html")) # 404
# Trochę nie mam pomysłu jak to testować, co może pójść nie tak? To chyba są tylko dwa ify? Czy to musi tak napierdalać całą stronę? Czy on nie może sobie gdzieś tam skrycie zwrócić tego objektu BeautifulSoup?
#To link do doskonałej inwestycji:
#https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-wtorny/mieszkanie-2-pokoje-gdynia-doskonala-inwestycja-ogl64070755.html
#używając funkcji z poprzedniego zadania utwórz obiekt BeautifulSoup z powyższym linkiem.
# print(url_validator("https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-wtorny/mieszkanie-2-pokoje-gdynia-doskonala-inwestycja-ogl64070755.html"))
#Napisz funkcję, która jako argument przyjmie obiekt BeautifulSoup i wyciągnie z niego cenę.
print('\n' + 'Zad. 2.')
def nedvizhimost_price_parser(soup):
price_span = soup.find('span', {"class": "oglDetailsMoney"})
price_output = (price_span.contents.pop(0))
cena = int(price_output.replace(" ", ""))
return cena
# link1 = "https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-wtorny/mieszkanie-2-pokoje-gdynia-doskonala-inwestycja-ogl64070755.html"
# link2 = "https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-pierwotny/mieszkanie-b32-sw-piotra-87-00m2-ogl64079118.html"
# link3 = "https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-wtorny/po-remoncie-gotowy-do-zamieszkania-200m2-ogrodu-ogl64109964.html"
# url_get = requests.get(link1, headers=agent)
# sup = BeautifulSoup(url_get.text, "lxml")
# print(nedvizhimost_price_parser(sup))
# url_get = requests.get(link2, headers=agent)
# sup = BeautifulSoup(url_get.text, "lxml")
# print(nedvizhimost_price_parser(sup))
# url_get = requests.get(link3, headers=agent)
# sup = BeautifulSoup(url_get.text, "lxml")
# print(nedvizhimost_price_parser(sup))
# print("\n" + "Wykorzystując url_validator z Zadania 1.:")
print(nedvizhimost_price_parser(url_validator("https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-wtorny/mieszkanie-2-pokoje-gdynia-doskonala-inwestycja-ogl64070755.html")))
print(nedvizhimost_price_parser(url_validator("https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-pierwotny/mieszkanie-b32-sw-piotra-87-00m2-ogl64079118.html")))
print(nedvizhimost_price_parser(url_validator("https://ogloszenia.trojmiasto.pl/nieruchomosci-rynek-wtorny/po-remoncie-gotowy-do-zamieszkania-200m2-ogrodu-ogl64109964.html")))
#Używaj metod z biblioteki BeautifulSoup takich jak find lub findall z odpowiednią klasą.
#W przeglądarce kliknij prawym na cenę -> zbadaj element i sprawdź jakiej klasy jest ten div/span
#Cena ma być podana jako int a nie jako string "239 000 zł"
#Znajdź 10 linków i uruchom na nich swoją metodę, czy wszystkie ceny we wszystkich linkach są pobrane bez błędów?
#Musi być 10? Nie nie musi. Dobrze by było zrobić ich wiecej jak 2 |
17fcaffaf0ef060efc8efdd572e9c98802867ee9 | dsabljak/Infmre | /prim_dijkstra.py | 3,959 | 3.859375 | 4 | class FileReader:
def __init__(self, path):
self.file = open(path, 'r')
self.nodes = set()
self.edges = []
self.edge_cost = dict()
self.parse()
"""
Data is written in .txt file like:
begin_node, end_node, cost, direction;
This method parses all rows of file and saves data
"""
def parse(self):
data = self.file.readlines()
for row in data:
begin_node = row.split(',')[0]
end_node = row.split(', ')[1]
edge = begin_node + end_node
cost = int(row.split(', ')[2])
direct = row.split(', ')[3].split(';')[0]
self.nodes.add(begin_node)
self.nodes.add(end_node)
self.edges.append(edge)
# If cost is 0, ignore it
# Maybe not the best way?
if cost != 0:
self.edge_cost[edge] = cost
# If direction is not directed, then create simetric edge
# For example AB -> BA
if direct == 'n':
self.edge_cost[edge[::-1]] = cost
print(self.nodes)
print(self.edges)
print(self.edge_cost)
# Function for getting all possible combinations for edges by nodes
# For example [a, b] returns set {bb, aa, ab, ba} (using set to avoid redundancy)
def get_all(nodes):
return set([x + y for x in nodes for y in nodes] + [y + x for x in nodes for y in nodes])
path = input("Insert path to file with data:")
data = FileReader(path)
nodes = data.nodes
edges = data.edges
edge_cost = data.edge_cost
used_nodes = []
used_edges = []
current_node = nodes.pop()
used_nodes.append(current_node)
print(f"Odabrani početak: {current_node}")
total_cost = 0
temp_edge_cost = dict() # on class this is "dist" in table
while len(nodes) != 0:
print(f"Neobiđeni vrhovi: {nodes}")
for edge in edge_cost.keys():
if current_node == edge[0]:
if edge[1] not in used_nodes: # if watched node is already in used nodes, we do not need it
print(f"Rub koji razmatram: {edge}")
print(f"Vrh koji razmatram: {edge[1]}")
print(f"Obiđeni vrhovi: {used_nodes}")
temp_edge_cost[edge] = edge_cost[edge]
print(f"Ovo su privremeni vrhovi i udaljenosti: {temp_edge_cost}")
min_edge = min(temp_edge_cost, key=temp_edge_cost.get)
print(f"Minimalnu udaljenost ima: {min_edge} s udaljenosti {edge_cost[min_edge]}")
print(f"Ovo su iskorišteni bridovi: {used_edges}")
if min_edge not in used_edges or min_edge[::-1] not in used_edges: # checking edge witch is being added and it's simetric also, if not used already, add it
print(f"{min_edge} i {min_edge[::-1]} nije u {used_edges} pa ga dodajem")
used_edges.append(min_edge)
print(f"Sada iskoristeni bridovi zgledaju ovako: {used_edges}")
print(f"Nema smisla cuvati {min_edge} i {min_edge[::-1]} u privremenim udaljenostima: {temp_edge_cost} pa ga izbacujem")
temp_edge_cost.pop(min_edge) #need to delete that edge from "dist" column to avoid using it again later
try:
temp_edge_cost.pop(min_edge[::-1])
except:
pass
print(f"Sada izgledaju ovako: {temp_edge_cost}")
total_cost += int(edge_cost[min_edge])
current_node = min_edge[1]
print(f"Trenutni vrh je: {current_node}")
used_nodes.append(current_node)
print(f"Iskorišteni vrhovi su sada: {used_nodes}")
edges_for_deletion = set(get_all(list(used_nodes))) # combining all used nodes to get edges which need to be deleted so they don't get used again later
print(f"Treba pobrisati: {edges_for_deletion}")
for edge_for_deletion in edges_for_deletion:
try:
temp_edge_cost.pop(edge_for_deletion)
except:
pass
print(f"Nakon brisanja: {temp_edge_cost}")
nodes.remove(current_node)
print(used_edges)
print(total_cost)
|
3724701e57901b5e393f06e95345e8ea9cd777fc | rfrusina/CS115-FreshmanYR | /hw8.py | 1,343 | 3.625 | 4 | '''
Created on Mar 27, 2017
@author: Robert Frusina
I pledge my honor I have abided by the Stevens Honor System
'''
def binaryToNum(s):
'''returns string back to n'''
if s == '':
return 0
elif int(s[0]) == 1:
return binaryToNum(s[1:]) + 2 ** len(s[:-1])
return binaryToNum(s[1:]) + 0
def TcToNum(s):
'''takes as input a string of 8 bits representing an integer
in two's-complement, and returns the corresponding integer'''
if s=='':
return 0
elif s[0]=='1':
return binaryToNum(s[1:])-128
else:
return binaryToNum(s[1:])
def isOdd(n):
''' determines if n is odd'''
if n % 2 == 0:
return False
return True
def numToBinary(n):
'''take a number n and converts it to binary'''
if n == 0:
return ''
elif isOdd(n):
return numToBinary(n//2) +'1'
return numToBinary(n//2) + '0'
def padder(S):
'''zeros added to string'''
padded=7-len(S)
return padded*'0'+ S
def NumToTc(n):
'''takes as input an integer N, and returns a string representing
the two's-complement representation of that integer'''
if n>=128 or n<=-129:
return 'Error'
if n==0:
return 8*'0'
if n<0:
return '1'+padder(numToBinary(128-abs(n)))
else:
return '0' + padder(numToBinary(n)) |
4653e0632b19a0cae5be690df926119884413692 | rfrusina/CS115-FreshmanYR | /life.py | 2,794 | 3.640625 | 4 | #
# life.py - Game of Life lab
#
# Name:Robert Frusina
# Pledge:I pledge my honor that I have abided by the Stevens Honor System
#
import random
import sys
def createOneRow(width):
"""Returns one row of zeros of width "width"...
You should use this in your
createBoard(width, height) function."""
row = []
for col in range(width):
row += [0]
return row
def createBoard(width, height):
A = []
for row in range(height):
A += [createOneRow(width)]
return A
def printBoard(A):
for row in A:
for col in row:
sys.stdout.write( str(col) )
sys.stdout.write( '\n' )
def diagonalize(width,height):
A = createBoard(width, height)
for row in range(height):
for col in range(width):
if row == col:
A[row][col] = 1
else:
A[row][col] = 0
return A
def innerCells(width,height):
A = createBoard(width, height)
for row in range(height):
for col in range(width):
if row == height - 1 or row == 0 or col == 0 or col == width - 1:
A[row][col] = 0
else:
A[row][col] = 1
return A
def randomCells(width,height):
A = createBoard(width, height)
for row in range(height):
for col in range(width):
if row == height - 1 or row == 0 or col == 0 or col == width - 1:
A[row][col] = 0
else:
A[row][col] = random.choice( [1,0] )
return A
def copy(A):
newA = []
for row in A:
if type(row) is list:
newA.append(copy(row))
else:
newA.append(row)
return newA
def innerReverse(A):
height = (len(A))
width = len(A[0])
for row in range(height):
for col in range(width):
if row == height - 1 or row == 0 or col == 0 or col == width - 1:
A[row][col] = 0
elif A[row][col] == 0:
A[row][col] = 1
else:
A[row][col] = 0
return A
def countNeighbors(row,col,A):
count = 0
for r in range(row - 1, row + 2):
for c in range(col - 1, col + 2):
count += A[r][c]
count -= A[row][col]
return count
def next_life_generation(A):
newA = copy(A)
height = (len(newA))
width = len(newA[0])
for row in range(height):
for col in range(width):
if row == height - 1 or row == 0 or col == 0 or col == width - 1:
A[row][col] = 0
elif countNeighbors(row, col, A) < 2:
A[row][col] = 0
elif countNeighbors(row, col, A) > 3:
A[row][col] = 0
elif countNeighbors(row, col, A) == 3:
A[row][col] = 1
return newA |
42d46f187e8086acd5c56b1f8151f9697189757d | MarkEra02/Python-Task1 | /Test.py | 167 | 3.921875 | 4 | from itertools import permutations
print('Enter letters: ')
arr = input().split()
print('Result: ')
for letter in permutations(arr, ):
print(letter)
|
ad61a3ff4da961d60f8caa62d2ea9a9f14bf6a57 | hawaicai/pp4e | /Preview/cgitest.py | 763 | 3.625 | 4 | # 主html模板
fieldnames = ('name', 'age', 'job', 'pay')
replyhtml = """
<html>
<title>People Input Form</title>
<body>
<form method=POST action="cgi-bin/peoplecgi.py">
<table>
<tr><th>Key <td><input type=text name=key value="%(key)s">
$ROWS$
</table>
<P>
<input type=submit value="Fetch", name=action>
<input type=submit value="Update", name=action>
</form>
</body>
</html>
"""
# 为$ROW$的数据行插入html
rowhtml = '<tr><th>%s<td><input type=text name=%s value="%%(%s)s">\n'
rowshtml = ''
for fieldname in fieldnames:
rowshtml += (rowhtml % ((fieldname,) * 3))
print(rowshtml)
print('\n$$$$$$$$$$$$\n')
print(replyhtml)
replyhtml = replyhtml.replace('$ROWS$', rowshtml)
print('\n$$$$$$$$$$$$\n')
print(replyhtml)
|
ba8c76e2bb0930b9f97565504c2780d51da08b34 | alexyvassili/devman-async | /lesson-2/physics/collisions.py | 2,290 | 3.984375 | 4 | """
Collisions module. Manage objects collisions.
"""
from typing import Dict, Coroutine, Optional
from objects.animations import Fire, SpaceShip
from objects.space_garbage import Garbage
def _is_point_inside(corner_row: int, corner_column: int,
size_rows: int, size_columns: int,
point_row: int, point_row_column: int) -> bool:
rows_flag = corner_row <= point_row < corner_row + size_rows
columns_flag = corner_column <= point_row_column < corner_column + size_columns
return rows_flag and columns_flag
def has_collision(obstacle_corner: tuple, obstacle_size: tuple,
obj_corner: tuple, obj_size=(1, 1)) -> bool:
"""Determine if collision has occured.
Returns True or False.
"""
opposite_obstacle_corner = (
obstacle_corner[0] + obstacle_size[0] - 1,
obstacle_corner[1] + obstacle_size[1] - 1,
)
opposite_obj_corner = (
obj_corner[0] + obj_size[0] - 1,
obj_corner[1] + obj_size[1] - 1,
)
return any([
_is_point_inside(*obstacle_corner, *obstacle_size, *obj_corner),
_is_point_inside(*obstacle_corner, *obstacle_size, *opposite_obj_corner),
_is_point_inside(*obj_corner, *obj_size, *obstacle_corner),
_is_point_inside(*obj_corner, *obj_size, *opposite_obstacle_corner),
])
def find_collision(fire: Fire, obstacles: Dict[Coroutine, Garbage]) -> Optional[Coroutine]:
"""Find collisions garbage and spaceship fire."""
fire_coords = fire.row, fire.column
for obstacle_coro, obstacle in obstacles.items():
obstacle_corner = obstacle.row, obstacle.column
if has_collision(obstacle_corner, obstacle.size, fire_coords):
return obstacle_coro
return None
def find_spaceship_collision(spaceship: SpaceShip, obstacles: Dict[Coroutine, Garbage]) -> Optional[Coroutine]:
"""Game Over when we have collision of spaceship and garbage."""
spaceship_coords = spaceship.row, spaceship.column
for obstacle_coro, obstacle in obstacles.items():
obstacle_corner = obstacle.row, obstacle.column
if has_collision(obstacle_corner, obstacle.size,
spaceship_coords, spaceship.size):
return obstacle_coro
return None
|
6f8a2d22c6fb18271baa0d6444ec18a73998ccb8 | Moloch540394/machine-learning-hw | /learning-curve/featureNormalization.py | 420 | 3.515625 | 4 | """Normalize the training set data for multiple."""
__author__="Jesse Lord"
__date__="January 8, 2015"
import numpy as np
def featureNormalization(X):
X_norm = X
shape = X.shape
mu = np.empty(shape[1])
sigma = np.empty(shape[1])
for ii in range(shape[1]):
mu[ii]=np.mean(X[:,ii])
sigma[ii]=np.std(X[:,ii])
X_norm[:,ii] = (X[:,ii]-mu[ii])/sigma[ii]
return (X_norm,mu,sigma)
|
de7f2d2afcb130e6d5484bdbad0795fbf54bdf2f | Moloch540394/machine-learning-hw | /linear-regression/driver.py | 1,398 | 4.3125 | 4 | """Computes the linear regression on a homework provided data set."""
__author__="Jesse Lord"
__date__="January 8, 2015"
import numpy as np
import matplotlib.pyplot as plot
from computeCost import computeCost
from gradientDescent import gradientDescent
from featureNormalization import featureNormalization
import readData
nfeatures = 2
if __name__=="__main__":
if nfeatures == 1:
(x,y,nexamples) = readData.readSingleFeature()
elif nfeatures == 2:
(x,y,nexamples) = readData.readMultiFeature()
# transforming the X array into a matrix to simplify the
# matrix multiplication with the theta_zero feature
X = np.ones((nfeatures+1,nexamples))
X[1:,:]=x[:,:]
theta = np.zeros(nfeatures+1)
if nfeatures==2:
(X_norm,mu,sigma) = featureNormalization(X)
# computes the cost as a test, should return 32.07
print computeCost(X_norm,y,theta)
if nfeatures == 1:
iterations = 1500
elif nfeatures == 2:
iterations = 400
alpha = 0.01
# computes the linear regression coefficients using gradient descent
theta = gradientDescent(X_norm,y,theta,alpha,iterations)
print theta[0]+theta[1]*((1650-mu[0])/sigma[0])+theta[2]*((3-mu[1])/sigma[1])
if nfeatures==1:
plot.plot(x,y,'o',x,np.dot(theta,X))
plot.show()
#plot.plot(x[0,:],y,'o',x[0,:],np.dot(theta[:1],X[:1,:])
#plot.show()
|
2d331bc3cd3b5d2410a7ec4b39b1ecf0da2aac7b | Moloch540394/machine-learning-hw | /learning-curve/plotData.py | 2,498 | 3.8125 | 4 | """Plots the scatter plot of the logistic regression training set."""
__author__="Jesse Lord"
__date__="January 8, 2015"
import matplotlib.pyplot as p
import numpy as np
from polyFeatures import polyFeatures
def plotPoints(x,y):
p.scatter(x,y,marker='x')
p.show()
def plotTheta(X,y,theta):
p.scatter(X,y,marker='x')
plotx = np.array([np.amin(X),np.amax(X)])
degree = theta.size-1
ploty = np.zeros(2) + theta[0]
for ii in range(1,degree+1):
ploty += theta[ii] * (plotx**ii)
p.plot(plotx,ploty)
p.show()
def plotNorm(X,y,theta,mu,sigma):
"""Plots the data and best fit curve for polynomial features."""
p.scatter(X[:,0],y[:,0],marker='x')
# finding the range of x-values
xstart = np.amin(X[:,0])
xstop = np.amax(X[:,0])
step = (xstop-xstart)/100.
# extending the range of the x values
xstart -= step*10
xstop += step*10
xplot = np.arange(xstart,xstop,step)
# reshaping into a [100,1] array, since polyFeatures assumes this shape
xplot = np.reshape(xplot,[xplot.size,1])
degree = theta.size-1
xpoly = polyFeatures(xplot,degree)
for ii in range(degree):
xpoly[:,ii] -= mu[ii]
xpoly[:,ii] /= sigma[ii]
# endfor
# adding the bias unit for the dot product with theta
ndims = xpoly.shape
X = np.ones([ndims[0],ndims[1]+1])
X[:,1:] = xpoly
yplot = np.dot(theta,np.transpose(X))
p.plot(xplot,yplot,'r')
p.show()
def plotError(error_train,error_cv,x=None,xlabel=None):
"""Plots the training error and cross validation error for a given range of parameters. If no x-axis is sent to function then it is assumed to be learning curve with number of training examples as x-axis."""
if x is None:
n = len(error_train)
x = np.arange(n)+1
p.plot(x,error_train,'g',linewidth=3,label='Training set error')
p.plot(x,error_cv,'b',linewidth=3,label='Cross-Validation set error')
# setting the maximum and minimum range of the plotted y-axis equal
# to 2 and 0.5 times the maximum and minimum
# median of the errors, respectively
median_train = np.median(error_train)
median_cv = np.median(error_cv)
ymax = 2.0*max([median_train,median_cv])
ymin = 0.5*min([median_train,median_cv])
if ymin < 0:
ymin = 0.0
p.ylim(ymin,ymax)
if xlabel is None:
p.xlabel('Number of training examples')
else:
p.xlabel(xlabel)
p.ylabel('Error in data sets')
p.legend()
p.show()
|
4d8bf0b3222966abd08a62857b964c0b20ba0e61 | Moloch540394/machine-learning-hw | /linear-regression/gradientDescent.py | 696 | 3.890625 | 4 | """Computes the gradient descent for linear regression with multiple features."""
__author__="Jesse Lord"
__date__="January 8, 2015"
import numpy as np
from computeCost import computeCost
import matplotlib.pyplot as p
# turn on to compute cost function for each iteration as a debug
plotJ = 0
def gradientDescent(X,y,theta,alpha,num_iters):
m = len(y)
nfeatures = len(theta)
J_history = np.zeros(num_iters)
for ii in range(num_iters):
for jj in range(nfeatures):
theta[jj] -= alpha*sum((np.dot(theta,X)-y)*X[jj,:])/m
if plotJ:
J_history[ii] = computeCost(X,y,theta)
if plotJ:
p.plot(J_history)
p.show()
return theta
|
550820b826cc481f592b46a4c374fe38b0eb1b8b | benkhattab/MachineLearning | /009BoxPlot.py | 620 | 3.546875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('datasets/customer-churn-model/Customer Churn Model.txt')
plt.boxplot(data['Day Calls'])
plt.ylabel('Numero de llamadas diarias')
plt.title('Boxplot de las llamadas diarias')
print(data['Day Calls'].describe())
# Rango intercuartilico
IQR = data['Day Calls'].quantile(0.75) - data['Day Calls'].quantile(0.25)
print(f'Interquartile Range => {IQR}')
# Bigote inferior
lower = data['Day Calls'].quantile(0.25) - 1.5*IQR
print(lower)
# Bigote superior
higher = data['Day Calls'].quantile(0.75) + 1.5*IQR
print(higher)
plt.show() |
f391bade850d17f22c8cc6305b8e181390682ec9 | benkhattab/MachineLearning | /025LinearRegressionTest.py | 3,197 | 3.59375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# y = a + b*x (linear regression model)
# x : 100 normal distributed values N(1.5, 2.5) Media => 1.5 desviacion tipica => 2.5
# ye = 5 + 1.9*x + e
# e will be normally distributed N(0, 0.8) Media => 0 desviacion tipica => 0.8
# np.random.seed(19940903)
x = 1.5 + 2.5 * np.random.randn(100) # 100 normally distributed values for 'x'
res = 0 + 0.8 + np.random.randn(100)
y_pred = 5 + 1.9*x # test prediction (model)
y_actual = 5 + 1.9*x + res # test distributed 'y' values
x_list = x.tolist() # Changing array to a lists to create a dataframe
y_pred_list = y_pred.tolist()
y_actual_list = y_actual.tolist()
y_mean = [np.mean(y_actual) for i in range(1, len(x_list) + 1)]
data = pd.DataFrame(
{
'x': x_list,
'y_actual': y_actual_list,
'y_prediccion': y_pred_list,
'y_mean': y_mean
}
)
print(data.head())
plt.plot(data['x'], data['y_prediccion'])
plt.plot(data['x'], data['y_actual'], 'ro')
plt.plot(data['x'], y_mean, 'g')
plt.title('Valor Actual vs Predicción')
plt.show()
# SSD => Suma de los Cuadrados de las Diferencias
# Distancia entre un punto disperso y la recta calculada
# SST => Suma de los Cuadrados Totales
# Distancia entre el punto disperso y y_media
# SSR => Suma de los Cuadrados de la Regresion
# Distancia entre el punto disperso y la recta calculada + distancia entr el puntp disperso y y_media
data['SSR'] = ( data['y_prediccion'] - np.mean(y_actual) )**2
data['SSD'] = ( data['y_prediccion'] - data['y_actual'] )**2
data['SST'] = ( data['y_actual'] - np.mean(y_actual) )**2
print(data.head())
print( f'SSR => {sum(data["SSR"])}' )
print( f'SSD => {sum(data["SSD"])}' )
print( f'SST => {sum(data["SST"])}' )
print( f'SSR+SSD = SST => {sum(data["SSR"]) + sum(data["SSD"])}' )
print( f'R2 = SSR/SST => {sum(data["SSR"]) / sum(data["SST"])}' )
# CALCULANDO LA RECTA
# y = a + b*x
# b = sum( (xi - x_m)*(yi - y_m) ) / sum( (xi - x_m)^2 )
# a = y_m - b * x_m
print('\nCalculando la recta\n')
x_mean = np.mean(data['x'])
y_mean = np.mean(data['y_actual'])
print(f'x_mean => {x_mean}, y_mean => {y_mean}')
data['beta_n'] = (data['x']-x_mean)*(data['y_actual']-y_mean)
data['beta_d'] = (data['x']-x_mean)**2
beta = sum(data['beta_n']) / sum(data['beta_d'])
alpha = y_mean - beta * x_mean
print(f'alpha => {alpha}, beta => {beta}')
data['y_model'] = alpha + beta * data['x']
# print(data.head())
SSR = sum( (data['y_model']-y_mean)**2 )
SSD = sum( (data['y_model']-data['y_actual'])**2 )
SST = sum( (data['y_actual']-y_mean)**2 )
print(f'SSR => {SSR}')
print(f'SSD => {SSD}')
print(f'SST => {SST}')
print(f'SSR/SST => {SSR/SST}' )
y_mean = [np.mean(y_actual) for i in range(1, len(x_list) + 1)]
plt.plot(data['x'], data['y_prediccion'])
plt.plot(data['x'], data['y_actual'], 'ro')
plt.plot(data['x'], y_mean, 'g')
plt.plot(data['x'], data['y_model'])
plt.title('Valor Actual vs Predicción')
plt.show()
# RSE Error Estandar Residual
# RSE: Cuanto menor sea, mejor es el modelo
RSE = np.sqrt(SSD/(len(data)-2))
print(f'RSE = SSD/n-2 => {RSE}')
print(f'Porcentaje de error => {RSE/np.mean(data["y_actual"])}') |
1248d4aa0f0fcdb613782972fba43d20df509d96 | elvispy/PiensaPython | /1operaciones.py | 2,279 | 4.125 | 4 | ''' Existen varios tipos de operaciones en Python.
El primero, y mas comun es el de la adicion.
'''
x, y, z = 3, 9, '4'
a = 'String'
b = [1, 2, 'lol']
'''
La siguiente linea de codigo imprimira el resultado de sumar x con yield
'''
print(x+y)
'''
Debemos recordar que es imposible en la gran mayoria de los casos, sumar variables
de diferentes tipos. En ese caso, poner
print(x+z)
nos daria un error, puesto que z es del tipo string.
Sin embargo, es posible sumar dos listas
'''
c = [False, '123', 42]
print(b + c)
#la ultima linea seria parecido a b.extend(c)
#sin embargo, b.extend(c) es en realidad b = b + c. Asignandolo a b.
# Tambien podemos sumar strings, esto va a resultar en lo que se llama concatenacion
print(a + a)
'''
En general, la suma es de las pocas operaciones compartidas por distintos tipos.
El resto de operaciones, que listaremos a seguir son usadas mayoritariamente para
el tipo numerico
Resta (-):
6 - 5
Multiplicacion (*):
12 * 4
Division (/):
4 / 2
Potenciacion ( ^ ) :
3 ^ 4 (o, equivalentemente, pow(3, 4), o 3 ** 4 )
Resto de division ( % ) :
12 % 7 El resto de la division de 12 entre 7. En este caso es 5
'''
#OPERACIONES BOOLEANAS
'''
En ciertas ocaciones, necesitamos condicionar nuestro programa a mas
de una condicion. Consideremos el siguiente ejemplo:
Python, comprame una empanada si hay plata y si la despensa tiene
empanada de pollo.
Como le decimos a python que haga la instruccion?
Usando el operador and ( & )
'''
hay_plata = False
hay_empanada = True
comprar = hay_empanada and hay_plata #equivalentemente, hay_empanada & hay_plata
'''
El operador and recibe DOS booleans, y devuelve UNO. Este resultado sera verdadero
solamente si los dos booleans, sean verdadero, caso contrario devolvera Falso.
Otro operador muy comun es el operador booleano or ( | )
'''
print(hay_empanada or hay_plata) #equivalentemente, hay_empanada | hay_plata
'''
Un ultimo operador, es la negacion. Se pone al inicio del boolean, y lo cambia de sentido
'''
no_hay_plata = not hay_plata #sera Verdadero
'''
Recuerden que al igual que en matematicas, Python va a realizar lo que este dentro
de parentesis en primer lugar.
'''
print (not ( False and (True or True) ) )
#que va a imprimir la consola?
|
dc4da6b8c326529f76f9233c4b10311b8c9ecd76 | RanjankumarModi/RanjankumarModi-Turtle_Race | /turtle-race.py | 1,506 | 3.5 | 4 |
# coding: utf-8
# In[1]:
from turtle import *
from random import *
speed(50)
penup()
bgcolor("#94B3C6")
#penup()
goto(-150,100)
for i in range(15):
write(i)
right(90)
forward(10)
pendown()
forward(10)
penup()
forward(40)
pendown()
forward(10)
penup()
forward(40)
pendown()
forward(10)
penup()
forward(39)
pendown()
forward(10)
penup()
forward(35)
pendown()
forward(10)
penup()
backward(214)
left(90)
forward(30)
a=Turtle()
a.color('red')
a.shape("turtle")
a.penup()
a.goto(-160,-83)
a.pendown()
b=Turtle()
b.color('blue')
b.shape("turtle")
b.penup()
b.goto(-160,-35)
b.pendown()
c=Turtle()
c.color('black')
c.shape("turtle")
c.penup()
c.goto(-160,10)
c.pendown()
d=Turtle()
d.color('yellow')
d.shape("turtle")
d.penup()
d.goto(-160,60)
d.pendown()
for j in range(140):
a.forward(randint(1,5))
b.forward(randint(1,5))
c.forward(randint(1,5))
d.forward(randint(1,5))
l=[]
l.append(a.xcor())
l.append(b.xcor())
l.append(c.xcor())
l.append(d.xcor())
goto(70,-160)
pencolor("brown")
winner=max(l)
if(l[0]==winner):
write('RED is winner',align='center',font=("Comic Sans", 18, "bold"))
elif(l[1]==winner):
write('BLUE is winner',align='center',font=("Comic Sans", 18, "bold"))
elif(l[2]==winner):
write('BLACK is winner',align='center',font=("Comic Sans",18, "normal"))
elif(l[3]==winner):
write('YELLOW is winner',align='center',font=("Comic Sans", 18, "normal"))
|
4bb654640c6edc193f0e7abe1c20f4d359d1fb33 | jaeha13/TIL | /210709_python06/연습문제1.py | 154 | 3.8125 | 4 | height = int(input("height : "))
count_star = 0
for i in range(1, height + 1):
count_star += i
print("*" * i)
print("star 개수 : ", count_star)
|
a7fd52dcc52ebccf101687c588163ea852a638c1 | jaeha13/TIL | /210630_python02/conditionLab2.py | 1,060 | 3.640625 | 4 | """
실습 2
1. color_name 이라는 변수에 사용자로부터 칼라 이름을 하나 입력받는다.
2. 입력받은 칼라명이 red 이면 '#ff0000'이라는 문자열을 출력한다.
입력받은 칼라명이 red 가 아니면 '#000000'이라는 문자열을 출력한다.
1) input 함수를 통해 문자열을 압력받아 color_name 에 저장
2) if 조건문을 통해 color_name == red 인 경우 print 함수를 통해 '#ff0000' 출력
color_name != red 인 경우(else 인 경우) print 함수를 통해 '#000000' 출력
"""
# 파이썬은 대소문자 구분!!
# red != Red
color_name = input("색을 입력하시오: ")
if color_name == "red":
print("#ff0000")
else:
print("#000000")
"""
# ord('A') = 65 : ord('문자') : 아스키 코드를 숫자로 변환
# chr(65) = 'A' : chr(숫자) : 숫자를 아스키 코드로 변환
color_name = int(ord(input("색을 입력하시오: ")))
if color_name == "red":
print("#ff0000")
else:
print("#000000")
=> 결과
색을 입력하시오: r
#000000
""" |
e6c17dc992859aa066bbb31bbdcb092cba2123fd | jaeha13/TIL | /210713_python08/listLab8.py | 350 | 3.640625 | 4 | lst = [
['B', 'C', 'A', 'A'],
['C', 'C', 'B', 'B'],
['D', 'A', 'A', 'D']
]
data = {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
count_lst = []
for _, d in data.items():
count = 0
for row in lst:
count += row.count(d)
count_lst.append(count)
for i, d in data.items():
print(d, "는 ", count_lst[i], "개 입니다.", sep="")
|
254800377b27bcf30d98825ac1ee6c15569ab183 | jaeha13/TIL | /210719_python11/classLab1.py | 640 | 3.953125 | 4 | class Member:
def __init__(self):
self.name = None
self.account = None
self.passwd = None
self.birthyear = None
mem1 = Member()
mem2 = Member()
mem3 = Member()
mem1.name = "피치"
mem1.account = 1313
mem1.passwd = "3131"
mem1.birthyear = 1990
mem2.name = "릴리"
mem2.account = 1414
mem2.passwd = "4141"
mem2.birthyear = 1990
mem3.name = "데이지"
mem3.account = 1515
mem3.passwd = "5151"
mem3.birthyear = 1990
mem = {'1': mem1, '2': mem2, '3': mem3}
for i, member in mem.items():
print(f"회원{i}: {member.name}({member.account}, {member.passwd}, {member.birthyear})")
|
959bc56d6bf472999b93cd10dcdf16c07405187d | jaeha13/TIL | /210714_python09/funcLab12.py | 3,197 | 3.5625 | 4 | # version 3
# '구분자'.join(리스트) 함수를 이용 + map() 함수 이용해 Error 해결!!
def myprint(*args, **kwargs):
if len(args) == 0 and len(kwargs) == 0:
print("Hello Python")
else:
kwargs_dict = {"deco": "**", "sep": ","} # default 값 생성
kwargs_dict.update({k: v for k, v in kwargs.items()}) # kwargs 로부터 데이터 저장
# print 를 한번만 사용해서 출력하기 위해 args 요소들 사이에 sep 넣은 lst 만들기 using "구분자".join(리스트)
lst = list(args)
# (int) 숫자가 포함된 경우 Error 발생 => map() 함수를 이용하여 list 내 숫자를 string 으로 변환!!
str1 = kwargs_dict["sep"].join(map(str, lst))
print(kwargs_dict["deco"], str1, kwargs_dict["deco"], sep="") # deco 를 양 옆에 붙여서 *lst 출력
"""
# version 1 : join 함수를 사용하지 않고!!
def myprint(*args, **kwargs):
if len(args) == 0 and len(kwargs) == 0:
print("Hello Python")
else:
kwargs_dict = {"deco": "**", "sep": ","} # default 값 생성
kwargs_dict.update({k: v for k, v in kwargs.items()}) # kwargs 로부터 데이터 저장
# print 를 한번만 사용해서 출력하기 위해 args 요소들 사이에 sep 넣은 lst 만들기
lst = []
for i in range(len(args)):
if args[i] != args[-1]: # 제일 마지막에는 sep 이 들어가면 안됨!
lst.append(args[i]) # args 요소 하나 저장하고
lst.append(kwargs_dict["sep"]) # sep 하나 저장
else: # 제일 마지막 요소 뒤에는 아무것도 없이!
lst.append(args[i])
print(kwargs_dict["deco"], *lst, kwargs_dict["deco"], sep="") # deco 를 양 옆에 붙여서 *lst 출력
"""
"""
# version 2
# '구분자'.join(리스트) 함수 사용? Error!! 숫자가 포함된 case 의 경우 Error
def myprint(*args, **kwargs):
if len(args) == 0 and len(kwargs) == 0:
print("Hello Python")
else:
kwargs_dict = {"deco": "**", "sep": ","} # default 값 생성
kwargs_dict.update({k: v for k, v in kwargs.items()}) # kwargs 로부터 데이터 저장
# print 를 한번만 사용해서 출력하기 위해 args 요소들 사이에 sep 넣은 lst 만들기 using "구분자".join(리스트)
lst = list(args)
str1 = kwargs_dict["sep"].join(lst)
# Error
# Traceback (most recent call last):
# File "C:/jha/PYTHONexam/day9/funcLab12.py", line 35, in <module>
# myprint(10, 20, 30, deco="@", sep="-")
# File "C:/jha/PYTHONexam/day9/funcLab12.py", line 30, in myprint
# str1 = kwargs_dict["sep"].join(lst)
# TypeError: sequence item 0: expected str instance, int found
# => 원인: there are any non-string values in iterable, including bytes objects.
print(kwargs_dict["deco"], str1, kwargs_dict["deco"], sep="") # deco 를 양 옆에 붙여서 *lst 출력
"""
myprint()
myprint(10, 20, 30, deco="@", sep="-")
myprint("python", "javascript", "R", deco="$")
myprint("가", "나", "다")
myprint(100)
myprint(True, 111, False, "abc", deco="&", sep="")
|
b923c92371e62b576bb23e2c72d615fd1952fd0b | abhishek-kumaryadav/CSL443_LabAssignment1 | /prg1.py | 666 | 3.8125 | 4 | import sys
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def find_divisors(arr):
if len(arr) == 0:
return
else:
gccd = arr[0]
for i in range(1, len(arr) - 1):
gccd = gcd(gccd, arr[i])
divisors = set()
i = 1
while i * i <= gccd:
if gccd % i == 0:
divisors.add(i)
divisors.add(int(gccd / i))
i += 1
return divisors
def main():
arr = [int(i) for i in sys.argv[2:]]
divisors = find_divisors(arr)
print(" ".join(str(x) for x in sorted(divisors)), end="")
if __name__ == "__main__":
main()
|
f83faaceaf3db8ffcd1fc02bfae30051a852ce53 | lreedm1/practice | /main.py | 1,077 | 3.59375 | 4 | # credit to source - https://dev.to/insidiousthedev/make-a-simple-text-editor-using-python-31bd
from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
from tkinter.messagebox import *
from tkinter.font import Font
from tkinter.scrolledtext import *
import file_menu
import edit_menu
'''
import fomrat_menu
import help_menu
'''
#create the main window
root = Tk()
root.title("Text Editor")
#define the size of the window
root.geometry("800x600")
root.minsize(300,300)
#define the scrollbar behavior
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
#define the text widget
text = Text(root, yscrollcommand=scrollbar.set)
text.pack(fill=BOTH, expand=1)
scrollbar.config(command=text.yview)
#define the font
font = Font(family="Arial", size=14)
text.config(font=font)
#create the menu bar
menubar = Menu(root)
#add menus to the menu bar
file_menu.main(root, text, menubar)
edit_menu.main(root, text, menubar)
#format_menu.main(root, text, menubar)
#help_menu.main(root, text, menubar)
#run the main window
root.mainloop() |
e1562e9c8b9026001f3a1adcc645f78737ebb9aa | saintEvol/rigger_singleton | /rigger_singleton/singleton.py | 2,028 | 3.578125 | 4 | """
通过覆盖类的__new__和__init__方法提供单例支持
"""
# class Singleton:
# """
# 单例装饰器
# """
# __slots__ = (
# "__instance",
# "__is_instance_initialized",
# "__old_new_func",
# "__old_init_func",
# # "__cls__"
# )
#
# def __init__(self):
# self.__instance = None
# self.__is_instance_initialized = False
#
# def __call__(self, cls):
# print(cls)
#
# # 存储原有的__new__函数与__init__函数
# self.__old_new_func = cls.__new__
# self.__old_init_func = cls.__init__
#
# def new_new_func(cls1, *args, **kwargs):
# if self.__instance is None:
# self.__instance = self.__old_new_func(cls1, *args, **kwargs)
#
# return self.__instance
#
# def new_init_func(self1, *args, **kwargs):
# if not self.__is_instance_initialized:
# self.__old_init_func(self1, *args, **kwargs)
# self.__is_instance_initialized = True
#
# # 替换类函数
# cls.__new__ = new_new_func
# cls.__init__ = new_init_func
#
# return cls
def singleton(cls):
"""
单例模式的装饰器
:param cls:
:return:
"""
# 存储单例类的实例(实际上一个类只会有一个实例)
_instance = []
# 存储原来的__new__和__init__函数
_old_new = cls.__new__
_old_init = cls.__init__
# 重写原来的__new__与__init__函数
def _new_new(cls1, *args, **kwargs):
if len(_instance) <= 0:
_instance.append((_old_new(cls1, *args, **kwargs), False))
inst, dummy = _instance[0]
return inst
def _new_init(self, *args, **kwargs):
inst, if_inited = _instance[0]
if if_inited:
pass
else:
_old_init(self, *args, **kwargs)
_instance[0] = self, True
# 替换
cls.__new__ = _new_new
cls.__init__ = _new_init
return cls
|
68a28b6a23cb2aa70a6616060c9aced9b0ab0178 | kajusK/Advent-of-Code-2017 | /01.py | 312 | 3.515625 | 4 | #!/usr/bin/python3
import fileinput
import re
for line in fileinput.input():
sum = 0
line = re.sub(r'\s', '', line)
for i in range(0, len(line)-1):
if (line[i] == line[i+1]):
sum += int(line[i])
if line[0] == line[len(line)-1]:
sum += int(line[0])
print(sum)
|
cb9fdfe34faa657f6ca4964ec6c633c76a70749f | KamranMostafavi/PythonGraphs | /09_graph_decomposition_starter_files_2/toposort/toposort.py | 1,538 | 3.890625 | 4 | #Uses python3
'''
author: Kamran Mostafavi
given n courses and m directed edges between them representing pre-requisites
create a linearly ordered list of courses (topological order)
it is given that the graph of the courses is a DAG.
input:
n m
edge 1
.
.
edge m
output:
linearly ordered list of n courses
'''
import sys
class graph:
def __init__ (self, adj, n):
self.adj=adj
self.n=n
self.visited=[0 for _ in range (n)]
self.order=[]
def explore(self, v):
'''
explore graph starting at vertix v using the adjaceny list,
mark vertix as visted if able to reach
return linear order once done
'''
if self.visited[v]==1:
return
self.visited[v]=1
for neighbor in adj[v]:
self.explore(neighbor)
self.order.insert(0,v) #linear order vertix - find a sink and backtrace
return
def toposort(adj, n):
g=graph(adj,n)
for vertix in range (n):
g.explore(vertix)
return g.order
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
order = toposort(adj,n)
for x in order:
print(x + 1, end=' ')
|
e61894b1151754ca26648f6d352a5f95f349d167 | MaxKKuznetsov/FaceID_app | /Utility/timer.py | 2,552 | 3.59375 | 4 | import time
from datetime import datetime
from Utility.MainWinObserver import MainWinObserver
from Utility.MainWinMeta import MainWinMeta
def elapsed(func):
def wrapper():
start = datetime.now()
func()
end = datetime.now()
elapsed = (end - start).total_seconds() * 1000000
print(f'>> функция {func.__name__} время выполнения (mks): {elapsed}')
return wrapper
def elapsed_1arg(func):
def wrapper(arg):
start = datetime.now()
func(arg)
end = datetime.now()
elapsed = (end - start).total_seconds()
print(f'>> функция {func.__name__} время выполнения (s): {elapsed}')
return wrapper
def elapsed_2arg(func: object) -> object:
"""
:rtype: object
"""
def wrapper(arg1, arg2):
start = datetime.now()
func(arg1, arg2)
end = datetime.now()
elapsed = (end - start).total_seconds()
print(f'>> функция {func.__name__} время выполнения (mks): {elapsed}')
return wrapper
def elapsed_3arg(func):
def wrapper(arg1, arg2, arg3):
start = datetime.now()
func(arg1, arg2, arg3)
end = datetime.now()
elapsed = (end - start).total_seconds()
print(f'>> функция {func.__name__} время выполнения (mks): {elapsed}')
return wrapper
def timer4detector(detector, detect_fn, images, *args):
start = time.time()
faces = detect_fn(detector, images, *args)
elapsed = time.time() - start
print(f', {elapsed:.3f} seconds')
return faces, elapsed
class Timer(MainWinObserver, metaclass=MainWinMeta):
def __init__(self, inModel):
"""
:type inModel: object
"""
self.start_timer()
# self.start_timer()
# self.dt = 0
self.mModel = inModel
self.modelIsChanged()
# регистрируем представление в качестве наблюдателя
self.mModel.addObserver(self)
def modelIsChanged(self):
"""
Метод вызывается при изменении модели.
"""
# self.return_time()
# print(self.mModel.state)
# print('time end: %s' % str(self.return_time()))
self.stop_timer()
self.start_timer()
def start_timer(self):
self.t_start = time.time()
def stop_timer(self):
self.t_start = 0
def return_time(self):
return time.time() - self.t_start
|
f9e304feb4824241876ba1aa59667540bcdf30b2 | somersaultjump/blackjack | /cards.py | 2,062 | 3.921875 | 4 | """Cards module defines classes specifically for the card game Blackjack."""
import random
suits = (
'Hearts', 'Diamonds', 'Spades', 'Clubs'
)
ranks = (
'Two','Three','Four','Five','Six','Seven',
'Eight','Nine','Ten','Jack','Queen','King',
'Ace'
)
values = {
'Two':2,'Three':3,'Four':4,'Five':5,
'Six':6,'Seven':7,'Eight':8,'Nine':9,
'Ten':10,'Jack':10,'Queen':10,'King':10,
'Ace':11
}
class Card():
def __init__(self,rank,suit,hidden=False):
self.rank = rank
self.suit = suit
self.value = values[rank]
self.hidden = hidden
self.hrank = "????"
self.hsuit = "??????"
self.hvalue = 0
def __str__(self):
if self.hidden == True:
return self.hrank + " of " + self.hsuit
else:
return self.rank + " of " + self.suit
# add functionality to hide card properties, as if its facedown.
def hide(self):
self.hidden = True
def show(self):
self.hidden = False
class Deck():
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
self.all_cards.append(Card(rank,suit))
random.shuffle(self.all_cards)
def deal_card(self):
return self.all_cards.pop(0)
class Player():
def __init__(self,name="Player"):
self.name = name
self.all_cards = []
self.money = 100
def add(self,amount):
self.money += amount
def deduct(self,amount):
self.money -= amount
def hand_value(self):
total = 0
for card in self.all_cards:
total += card.value
return total
def clear_hand(self):
self.all_cards[:]
class Pot():
def __init__(self):
self.amount = 0
def __str__(self):
return f"Pot contains {self.amount} dollars."
def add(self,amount):
self.amount += amount
def deduct(self,amount):
self.amount -= amount
def empty(self):
self.amount = 0 |
197ba92c966f62034b35c657c601e82e557b1fd3 | devChuk/Graphics_Engine | /parts/line/draw.py | 1,882 | 4.09375 | 4 | from display import *
from matrix import *
#Go through matrix 2 entries at a time and call
#draw_line on each pair of ponts
def draw_lines( matrix, screen, color ):
[draw_line(screen, a[0], a[1], b[0], b[1], color) for (a,b) in zip(matrix, matrix[1:]) if matrix.index(a) % 2==0]
#Add the edge (x0, y0, z0) - (x1, y1, z1) to matrix
def add_edge( matrix, x0, y0, z0, x1, y1, z1 ):
add_point(matrix, x0, y0, z0)
add_point(matrix, x1, y1, z1)
#Add the point (x, y, z) to matrix
def add_point( matrix, x, y, z=0 ):
matrix.append([x, y, z, 1])
#Plot all the pixels needed to draw line (x0, y0) - (x1, y1)
#to screen with color
def draw_line( screen, x0, y0, x1, y1, color ):
if (x0 == x1): #if the points are horizontal of each other.
y = y0
if(y0 > y1):
while( y >= y1):
plot(screen, color, x0, y)
y -= 1
else:
while( y <= y1):
plot(screen, color, x0, y)
y += 1
return
if (x0 > x1): #if the first point is to the right of the other, flip the points around.
x2 = x0
y2 = y0
x0 = x1
y0 = y1
x1 = x2
y1 = y2
A = y1 - y0
B = -(x1 - x0)
dy = y1-y0
dx = x1-x0
#Find the slope to determine the octants
if(dy > 0):
if(dx > dy):
octant = 1
else:
octant = 2
else:
if(dx > dy*-1):
octant = 8
else:
octant = 7
x = x0
y = y0
#Plot accordingally
if (octant == 1):
d = 2*A + B
while (x <= x1):
plot(screen, color, x,y)
if(d > 0):
y += 1
d += 2*B
x += 1
d += 2*A
if (octant == 2):
d = 2*B + A
while (y <= y1):
plot(screen, color, x,y)
if(d < 0):
x += 1
d += 2*A
y += 1
d += 2*B
if (octant == 8):
d = 2*A - B
while (x <= x1):
plot(screen, color, x,y)
if(d < 0):
y -= 1
d -= 2*B
x += 1
d += 2*A
else: #octant 7
d = -2*B + A
while (y >= y1):
plot(screen, color, x,y)
if(d > 0):
x += 1
d += 2*A
y -= 1
d -= 2*B |
87a2e702cf4651d33cd6668723a85b6618cdb636 | mahesh-mn-9040/Median-of-Two-Sorted-Arrays-Leetcode-Solution-in-Python | /med.py | 377 | 3.734375 | 4 |
nums1=list(map(int,input().split()))
nums2=list(map(int,input().split()))
mer=nums1+nums2
mer.sort()
x=len(mer)
if x==1:
return mer[0]
elif x%2==0: #if the merged list's length is even
return ((mer[x//2]+mer[x//2 -1])/2)
else:#if the merged length is odd
return mer[x//2 ]
|
a50cd98331ee471f9d9e1bcbc5bd53762387841f | LukasKodym/py-tests | /aritmetical_operations.py | 126 | 3.671875 | 4 | # %%
##
a = 3
a *= 2
print(a)
# %%
##
a = 7
b = a // 2
print(b)
b = a % 2
print(b)
# %%
##
a /= 2.3
print(a)
print(type(a))
|
e208c5221a02c7cb44cc739806cb1f7808c4c118 | LukasKodym/py-tests | /fibonacci.py | 376 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 22:18:29 2020
@author: lukas
"""
def fib(num: int):
a, b = 0, 1
for i in range(num):
a, b = b, a + b
return a
n = int(input('Który wyraz ciągu Fibonacciego policzyć?'
'\nPodaj numer wyrazu: '))
val = fib(n)
print('{}. wyraz ciągu wynosi: {}'.format(n, val))
|
d0817a90d2741583ac4688a605ee87acf26580fe | LukasKodym/py-tests | /set.py | 143 | 3.53125 | 4 | a = set([1, 2, 3, 4])
b = set([1, 3, 7, 9])
print(a.intersection(b))
print(a.union(b))
print(a.difference(b))
print(a.symmetric_difference(b))
|
483aa02841460aa6cb0e0442754f65376cd0daa3 | LukasKodym/py-tests | /spyder/14_instrukcje_warunkowe.py | 3,022 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# %%
##
version = 3.7
print(version)
# %%
##
version > 3
version <= 3
# %%
##
number = 1200
number > 1000
number == 1200
number == 1000
number != 1200
number != 1000
# %%
##
# if [warunek]:
# [instrukcja]
# %%
##
if 8 > 10:
print('Tak')
# %%
##
a = 8
if a > 10:
print('a > 10')
# %%
##
a = 20
if a > 10:
print('a > 10')
else:
print('a <= 10')
# %%
##
age = 27
if age < 18:
print('Nie masz uprawnień.')
else:
print('Dostęp przyznany')
# %%
##
age = 18
if age == 18:
print('Masz 18 lat.')
elif age < 18:
print('Nie masz uprawnień.')
else:
print('Dostęp przyznany')
# %%
##
age = int(input('Podaj ile masz lat: '))
if age == 18:
print('Masz 18 lat.')
elif age < 18:
print('Nie masz uprawnień.')
elif age > 18:
print('Dostęp przyznany')
# %%
## częć druga
print('Program uruchomiony...')
print("""Włam się do systemu, zgadując dwucyfrowy kod pin.
Numer pin składa się z cyfr: 0, 1, 2.""")
pin = input('Wprowadź nr pin: ')
if pin == '21':
print('Brawo, złamałes system.')
elif pin == '20':
print('Byłes blisko.')
else:
print('Nie zgadłes!')
# %%
##
pin = int(input('Wprowadź nr pin: '))
if pin == 21:
print('Brawo, złamałes system.')
elif pin == 20:
print('Byłes blisko.')
else:
print('Nie zgadłes!')
# %%
##
string = ' '
if string:
print('niepusty ciąg znaków')
else:
print('pusty ciąg znaków')
# %%
##
number = 0
if number:
print('liczba niezerowa')
else:
print('zero')
# %%
##
default_flag = False
if default_flag:
print('doszło do defaultu')
else:
print('nie doszło')
# %%
##
default_flag = True
if not default_flag:
print('nie doszło')
else:
print('doszło do defaultu')
# %%
##
saldo = 10000
klient_zweryfikowany = True
if saldo > 0 and klient_zweryfikowany:
print('Możesz wyplacic gotówkę')
else:
print('Nie możesz wypłacić gotówki')
# %%
##
saldo = 10000
klient_zweryfikowany = True
amount = int(input('Ile chcesz wypłacić gotówki? '))
if saldo > 0 and klient_zweryfikowany and saldo >= amount:
print('Możesz wyplacic gotówkę')
else:
print('Nie możesz wypłacić gotówki. \
Brak wystarczającej kwoty {}'.format(abs(saldo - amount)))
# %%
##
fakt = 'python jest łatwy i przyjemny'
lenght = len(set(list(fakt)))
if lenght < 20:
print('Mniej niż 20 unikalnych znaków.')
else:
print('Liczba unikalnych znaków jest większa lub równa 20.')
# %%
##
name = 'python'
if 'p' in name:
print('Znaleziono p')
else:
print('Nie znaleziono p')
# %%
##
tech = 'sas'
if tech == 'python':
flag = 'Dobry wybór'
else:
flag = 'Poszykaj czegos lepszego'
# %%
##
tech = 'python'
'dobry wybór' if tech == 'python' else 'poszukaj czegos lepszego'
# %%
##
text = 'jklsdfjlsdfjlksdjfsdljkdsiojuqmfdjklljskl'
'Zawiera' if text.find('q') else 'Nie zawiera'
# %%
##
text = 'jklsdfjlsdfjlksdjfsdljkdsiojuqmfdjklljskl'
if 'q' in text:
print('Zawiera')
else:
print('Nie zawiera')
|
b18b578b481a52ccc277879f66a372990f9212f6 | parsoli83/covid-19 | /predict_future_situation.py | 2,637 | 3.53125 | 4 | import matplotlib.pyplot as plt
from random import *
def score_finder(l_symp):
"""
this is how i measure the health_index:
fever: abs(your fever-37)*100 eg >>> 39.5==250
tiredness: a number between 0 and 10 *10
cough: a number between 0 and 10 *10
difficulty in breathing: a number between 0 and 10 *10
sneeze: a number between 0 and 5 *10
then add all the above scores
"""
#l_symp:[fever,tiredness,cough,difficulty in breathing,sneeze]
score=0
score+=abs(l_symp[0]-37)*100+l_symp[2]*10+l_symp[3]*10+l_symp[4]*10
return score
#NOTE IT:its just an unrealistic example and has no use in real treatment
l_cases=[
[[36,1,1,1,1],[37,2,2,2,2],[37,1,1,3,1],[37,0,0,0,0]],
[[37,1,1,1,1],[37.5,2,2,2,2],[38,1,1,3,1],[37,0,0,0,0]],
[[37.5,1,2,2,1],[38,2,2,2,2],[39,3,2,3,1],[38,2,2,2,0]],
[[38,2,2,2,1],[39,3,2,3,2],[39.5,3,3,3,2],[38,3,3,2,0]],
[[39,3,2,2,2],[40,3,2,3,2],[40,4,3,3,2],[39,3,2,2,1]],
[[40,3,3,3,2],[41,4,3,3,2],[42,4,4,3,2],[41,4,4,3,3]],
[[41,10,10,3,2],[41,10,10,10,2],[42,8,8,8,5],[41,8,9,4,3]],
]
#again i remind "l_cases" is unreal and we cant use it
def KNN(fever_,tiredness_,cough_,difficulty_in_breathing_,sneeze_):
l_score=[fever_,tiredness_,cough_,difficulty_in_breathing_,sneeze_]
health_index=score_finder(l_scores)
l_best=[float("inf"),float("inf"),float("inf")]
l_name=[0,0,0]
for i in range(len(l_cases)):
score=abs(health_index-score_finder(l_cases[i][0]))
if score<l_best[0]:
l_name[2]=l_name[1]
l_name[1]=l_name[0]
l_name[0]=i
l_best[2]=l_best[1]
l_best[1]=l_best[0]
l_best[0]=score
elif score<l_best[1]:
l_name[2]=l_name[1]
l_name[1]=i
l_best[2]=l_best[1]
l_best[1]=score
elif score<l_best[2]:
l_name[2]=i
l_best[2]=score
l_future=[[],[],[]]
for i in range(3):
for item in range(5):
score_item=0
for name in l_name:
score_item+=l_cases[name][i+1][item]
score_item=int(score_item/3*10)/10
l_future[i].append(score_item)
print("l_future:",l_future)
l_future_scores=[[score_finder(l_future[0])],[score_finder(l_future[1])],[score_finder(l_future[2])]]
plt.scatter(l_future_scores,[2,3,4])
plt.show()
l=["fever","tiredness","cough","difficulty in breathing","sneeze"]
l_scores=[]
for i in l:
inp=int(input(i+":"))
l_scores.append(inp)
KNN(l_scores[0],l_scores[1],l_scores[2],l_scores[3],l_scores[4])
#def prescription(l_future):
#35 |
036fce6a5697aa7753e482d08a55424b748818c3 | ZoolooS/python_crash_course | /09/09.10/restaurant.py | 704 | 3.71875 | 4 | '''
'''
# ====== imports block ================================== #
# ====== class declaration =========================== #
class Restaurant():
'''
'''
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(self.restaurant_name.title())
print(self.cuisine_type)
def open_restaurant(self):
print(f'{self.restaurant_name.title()} is open!')
def increment_number_served(self, served_per_day):
self.number_served += served_per_day
# ====== end of code ==================================== #
|
bb1e8f7a9c91ae286693eea6a6b4e8f9609d3a37 | ZoolooS/python_crash_course | /09/09.13/dice_roll.py | 532 | 3.75 | 4 | '''
'''
# ====== imports block ================================== #
from die import Die
# ====== class declaration ============================== #
# ====== main code ====================================== #
# my_die = Die()
# [print(f'Roll the die -> {my_die.roll_die()}') for i in range(10)]
# my_die = Die(10)
# [print(f'Roll the die -> {my_die.roll_die()}') for i in range(10)]
my_die = Die(20)
[print(f'Roll the die -> {my_die.roll_die()}') for i in range(10)]
# ====== end of code ==================================== #
|
f0960c0968d27b632b39b748602188917c82ade8 | ZoolooS/python_crash_course | /10/10.06/exceptions.py | 533 | 3.96875 | 4 | '''
'''
# ====== imports block ================================== #
# ====== function declaration =========================== #
def sum_with_check():
try:
n, m = int(input('Enter first number: ')), int(input('Enter second number: '))
except ValueError:
print('Well, you definetly insert not number...')
else:
print(f'The sum of {n} and {m} is {n + m}.')
# ====== main code ====================================== #
sum_with_check()
# ====== end of code ==================================== #
|
ee5dd01970036ea690570ade3080bf52f80a00f7 | ZoolooS/python_crash_course | /09/09.05/users.py | 1,687 | 3.703125 | 4 | '''
'''
class User():
'''
'''
def __init__(self, first_name, last_name, login, password, phone, about):
self.first_name = first_name
self.last_name = last_name
self.login = login
self.password = password
self.phone = phone
self.about = about
self.login_attempts = 0
def describe_user(self):
print(
f'{self.first_name.title()} {self.last_name.title()} '
f'has login - {self.login}.\n'
f'You can call by {self.phone}.\n'
f'{self.first_name.title()} wrote about him/her-self '
f'"{self.about}"'
)
def greet_user(self):
print(f'Hello, {self.first_name.title()} {self.last_name.title()}!')
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
# ====== imports block ================================== #
# ====== function declaration =========================== #
# ====== main code ====================================== #
user01 = User('Ilya', 'Popov', 'zooloos', 'qwerty', '+7-999-277-84-03', 'N/A')
# user02 = User('Kesha', 'Vorobey', 'Vorkesh', '12356', '+7-300-359-65-13', 'Не пою!')
# user03 = User('Stepan', 'Kaldera', 'goodone', 'asdfg', '+7-600-126-78-95', 'Щас спою!')
print(user01.login_attempts)
user01.increment_login_attempts()
user01.increment_login_attempts()
user01.increment_login_attempts()
user01.increment_login_attempts()
print(user01.login_attempts)
user01.reset_login_attempts()
print(user01.login_attempts)
# ====== end of code ==================================== #
|
e109b7148a49536bdc0d6f2d6fae3751d1a0c3cc | tmoraru/python-tasks | /less3.py | 498 | 4 | 4 | mytask = "Assign a list to variables temperatures. The list should contain three items, a float, an integer, and a string."
print(mytask)
temperatures = [7.5, 9, "today"]
print(temperatures)
mytask1 = "Assign a list to variables rainfall. The list should contain four items, a float, an integer, a string, and a list. Yes, there's nothing wrong with lists containig other lists. Lists can contain any type."
print(mytask1)
rainfall = [19.9, 1998, "taty" ,[1,2,3,4,5]]
print(rainfall) |
1a3bd1022273e086eeeb742ebace201d1aceceae | tmoraru/python-tasks | /less9.py | 434 | 4.1875 | 4 |
#Print out the slice ['b', 'c', 'd'] of the letters list.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[1:4])
#Print out the slice ['a', 'b', 'c'] of the letters list
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[0:3])
#Print out the slice ['e', 'f', 'g'] of the letters list.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[4:]) #or use the command print(letters[-3:])
|
b114e24ad11323aa0236e71fc955f2569315ff31 | liginv/LP3THW | /exercise41-50/ex42.py | 1,370 | 4.09375 | 4 | # Animals is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
# Dog has-a object called Animal
class Dog(Animal):
def __init__(self, name):
# Dog has-a name
self.name = name
# Cat has-a object called Animal
class Cat(Animal):
def __init__(self, name):
# Cat has-a name
self.name = name
# Person is-a class
class Person(object):
def __init__(self, name):
# Person has-a name
self.name = name
# Person has-a pet of some kind
self.pet = None
# Employee has-a object called Person
class Employee(Person):
def __init__(self, name, salary):
# ?? hmm what is this strange magic?
super(Employee, self).__init__()
# Employee has-a salary
self.salary = salary
# Fish is-a class
class Fish(object):
pass
# Salmon has-a object Fish
class Salmon(Fish):
pass
# Halibut has-a object Fish
class Halibut(Fish):
pass
# rover is-a Dog
rover = Dog("Rover")
# satan is-a Cat
satan = Cat("Satan")
# mary is-a Person
mary = Person("Mary")
# mary has-a pet satan
mary.pet = satan
# frank is-a employee; has-a salary
frank = Employee("Frank", 120000)
# frank has-a pet rover
frank.pet = rover
# flipper is-a Fish
flipper = Fish()
# coruse is-a Salmon
crouse = Salmon()
# harry is-a Halibut
harry = Halibut() |
d4076402594b83189895f19cdc4730f9bd5e9072 | liginv/LP3THW | /exercise11-20/ex15.py | 547 | 4.15625 | 4 | # Importing the function/module argv from sys library in python
from sys import argv
# Assigning the varable script & filename to argv function
script, filename = argv
# Saving the open function result to a variable txt.
# Open function is the file .txt file.
txt = open(filename)
# Printing the file name.
print(f"Here's your file {filename}:")
# Printing the content of the file.
print(txt.read())
# Closing the file.
txt.close()
# trying with inout alone.
file = input("Enter the file name: ")
txt1 = open(file)
print(txt1.read())
txt1.close() |
031e3daaf6c03e8ffda9c02138e29e1fe6f606a5 | liweicai990/learnpython | /Code/Basic/Basic09_a.py | 1,381 | 4.0625 | 4 | '''
功能:100以内的素数和
重点:自定义函数的使用、逻辑常量True和False、列表生成式
作者:薛景
最后修改于:2019/05/27
'''
# 函数就是把一段代码包含起来,然后起个名字,方便后面的程序反复使用的编程机制
def isPrime(n): # isPrime是函数名,后面的n是函数的形式参数
for i in range(2,n):
if n%i == 0:
return False
else:
return True
# 函数的使用必须遵循先定义后使用的原则,所以函数的定义必须写在主程序前面
# 方案一,使用循环语句,逐个判定,若是素数就进行累加
S = 0
for i in range(2,101):
if isPrime(i):
S += i
print("方案一:100以内所有素数的和为%d" % S)
# 方案二,构造100以内的素数的列表,然后直接使用sum函数进行求和
nums = [i for i in range(2,101) if isPrime(i)]
print("方案二:100以内所有素数的和为%d" % sum(nums))
'''
对方案二的补充说明:这种用于生成一个数列的式子,叫做列表生成式,举几个简单的例子:
[i for i in range(5)] # 结果为:[0, 1, 2, 3, 4]
[i**2 for i in range(5)] # 结果为:[0, 1, 4, 9, 16]
[i**2 for i in range(5) if i%2==0] # 结果为:[0, 4, 16]
对于生成拥有通项公式的数列,用起来实在是太爽了^_^
''' |
b5d8646c90f3b6c325df4ed31614600b02107c08 | liweicai990/learnpython | /Code/Turtle/Turtle02.py | 1,567 | 3.78125 | 4 | '''
功能:绘制同心圆
重点:随机数的概念、颜色的表示方法、range函数的用法、循环结构程序设计
作者:薛景
最后修改于:2019/05/27
'''
import turtle
from random import random
# 从random函数库中导入random函数,该函数可以一个生成[0,1)区间上的随机数
t = turtle.Turtle()
t.shape("turtle")
'''
为了防止后画的圆遮挡先画的圆,所以同心圆必须从大往小画,因此循环变量i的值,必须从
大往小递减。观察本程序中的range函数,可以发现第一个参数表示起始值,第二个参数表示
终止值(不被包含在产生的序列中),第三个表示递增量(如果是负数,生成的序列就是递减
的关系),大家可以调整程序中的range函数的参数为以下组合,试试看效果:
(10,5,-1) # 只绘制5个圆就结束了
(10,0,-2) # 同样绘制5个圆,递减速度加大
(5,0,-1) # 还是绘制5个圆,起始圆变小了
'''
for i in range(10, 0, -1):
t.goto(20*i, 0) # 移动海龟到圆上,goto函数的参数是平面坐标系的坐标(x,y)
t.setheading(90) # 调整方向,准备画圆
t.color(random(), random(), random())
# 上面的语句用来设置圆的颜色,三个0~1之间的数分别表示红色、绿色、蓝色的比重
t.begin_fill()
t.circle(20*i) # circle函数的参数为半径,其正负决定了往左还是往右画圆
t.end_fill()
'''
思考题:上面的程序,如何修改,就可以画出美丽的彩虹呢?
''' |
8aaab09f3b60c92e1b2ffa700e991086cdaf24d2 | liweicai990/learnpython | /Code/Leetcode/top-interview-questions-easy/String33.py | 1,141 | 4.21875 | 4 | '''
功能:整数反转
来源:https://leetcode-cn.com/explore/featured/card/top-interview-questions-easy/5/strings/33/
重点:整数逆序算法
作者:薛景
最后修改于:2019/07/19
'''
# 本题需要分成正数和负数两种情况讨论,所以我们用sign存下该数的符号,然后对其求绝
# 对值,再统一进行正整数的逆序算法,以化简问题难度
# 该方案战胜 88.27 % 的 python3 提交记录
class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x>=0 else -1 # 符号位
res = 0
x = abs(x) # 求绝对值
while x>0:
res = res*10 + x%10 # 求余数计算原数的最后一位,并计入结果
x = x // 10 # 通过整除,去掉原数的最后一位
res = sign * res
# 下方的代码是为了满足题目对结果范围的限定而编写的
if -2**31 <= res <= 2**31-1:
return res
else:
return 0
# 以下是本地测试代码,提交时只需复制上面的代码块即可
solution = Solution()
print(solution.reverse(-123)) |
a9825462671b83cbc3526074d5f226e64f822421 | liweicai990/learnpython | /Code/Turtle/Turtle03_a.py | 1,236 | 3.625 | 4 | '''
功能:绘制好多五角星
重点:自定义函数的用法、参数的作用
作者:薛景
最后修改于:2019/05/30
'''
import turtle, math, random
t = turtle.Turtle()
t.shape("turtle")
def drawStar(x, y, r, color, heading):
t.up() # 因为海龟移动过程中会留下痕迹,所以移动之前先提笔up,移动完毕再落笔down
t.goto(x, y)
t.down()
t.color(color)
t.setheading(heading)
edge=r*math.sin(math.radians(36))/math.sin(math.radians(126))
t.forward(r)
t.left(180-18)
t.begin_fill()
for i in range(5):
t.forward(edge)
t.right(72)
t.forward(edge)
t.left(144)
t.end_fill()
t.speed(10) # 因为星星太多了,所以加个速吧,1-10表示速度,0表示不显示动画
for i in range(20):
x, y = random.randint(-200, 200), random.randint(-200, 200) # 随机产生坐标
r = random.randint(10, 50) # 随机产生大小
color = (random.random(), random.random(), random.random()) # 随机产生颜色
heading = random.randint(0, 360) # 随机产生朝向
drawStar(x, y, r, color, heading) # 函数调用
|
e930214ab684ad820e9a19ecfc72b78609489ed8 | matt-barron/csci127-assignments | /exam_01/compression.py | 666 | 3.984375 | 4 | def compress_word(w):
"""
W is a parameter representing a word that is a string. This
function should remove the letters " A, E, I, O, U" from a word.
"""
newword = " "
vowels= ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
for i in range(len(w)):
if w[i] not in vowels :
newword= w[i] + newword
return newword[::-1]
print(compress_word("hello"))
print(compress_word("apple"))
def sentence(line):
linelist= line.split()
news=[]
for i in range(len(linelist)):
news.append(compress_word(linelist[i]))
return "".join(news)
print(sentence("i like apple pies")) |
845bea1a5bf32e076fa0136937bdf7d210dd377b | matt-barron/csci127-assignments | /hw_04/list.py | 1,588 | 4.0625 | 4 | import random
def build_random_list(size,max_value):
"""
Parameters:
size : the number of elements in the lsit
max_value : the max random value to put in the list
"""
l = [] # start with an empty list
# make a loop that counts up to size
i = 0
while i < size:
l.append(random.randrange(0,max_value))
# we could have written this instead of the above line:
# l = l + [random.randrange(0,max_value)]
i = i + 1
return l
print(build_random_list(10,99))
def locate(l,value):
i = 0
found_index=-1
for i in range(len(l)):
if l[i]==value:
found_index = i
break #breaks out of the current loop
i+=1
return found_index
print(locate([1,2,3,3,4,5,6],4))
print(locate([12,42,"pi",88],14))
def count(l,value):
i = 0
a=0
while i <= len(l)-1:
if l[i] == value:
a= a+1
i= i+1
return a
print(count([12,3,3,3,5,6,6],3))
def reverse(l):
i=0
a=-1
b=[]
while i<= len(l)-1:
b.append(l[a])
i+=1
a-=1
return b
print(reverse([4,2,2,1]))
print(reverse([1, 2, 3, 4, 50]))
def pal(l):
i=0
a=-1
b=[]
while i<= len(l)-1:
b.append(l[a])
i+=1
a-=1
if l == b:
return "true"
else:
return "false"
print(pal([4,2,2,4]))
def increasing(l):
increasing = True
i=0
while i <= len(l)-1:
if l[i]>l[i+1]:
increasing = False
break
i+=1
return increasing
print(increasing([1,9,1,1])) |
7106600daa9540e96be998446e8e199ffd56ec28 | rhino9686/DataStructures | /mergesort.py | 2,524 | 4.25 | 4 |
def mergesort(arr):
start = 0
end = len(arr) - 1
mergesort_inner(arr, start, end)
return arr
def mergesort_inner(arr, start, end):
## base case
if (start >= end):
return
middle = (start + end)//2
# all recursively on two halves
mergesort_inner(arr, middle + 1, end)
mergesort_inner(arr, start, middle)
## merge everything together
temp = [0 for item in arr]
temp_it = start
first_half_it = start
first_half_end = middle
second_half_it = middle + 1
second_half_end = end
## merge the two halves back into a temp array
while (first_half_it <= first_half_end and second_half_it <= second_half_end):
if arr[first_half_it] < arr[second_half_it]:
temp[temp_it] = arr[first_half_it]
first_half_it += 1
else:
temp[temp_it] = arr[second_half_it]
second_half_it += 1
temp_it += 1
##copy remainders/ only one of the two will fire at ay given time
while(first_half_it <= first_half_end):
temp[temp_it] = arr[first_half_it]
first_half_it += 1
temp_it += 1
while(second_half_it <= second_half_end):
temp[temp_it] = arr[second_half_it]
second_half_it += 1
temp_it += 1
## copy everything back into array
size = end - start + 1
arr[start:(start + size) ] = temp[start:(start + size)]
def quicksort(arr):
start = 0
end = len(arr) - 1
quicksort_inner(arr, start, end)
return arr
def quicksort_inner(arr, left, right):
## Base case
if left >= right:
return
#get a pivot point, in this case always use middle element
pivot_i = (left + right)//2
pivot = arr[pivot_i]
## partition array around pivot
index = partition(arr, left, right, pivot)
##recursively sort around index
quicksort_inner(arr, left, index-1)
quicksort_inner(arr, index, right)
def partition(arr, left, right, pivot):
while (left <= right):
while arr[left] < pivot:
left +=1
while arr[right] > pivot:
right -= 1
if left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return left
def main():
arr = [3,6,4,8,4,1,3,5,3]
arr2 = arr[:]
sorted_arr = mergesort(arr)
print(sorted_arr)
sorted_arr = quicksort(arr2)
print(sorted_arr)
if __name__ == "__main__":
main() |
8b54f8006c98b5e88b7dd655e8338bb4fe3ba02c | CyberSamurai/Test-Project-List | /count_words.py | 574 | 4.4375 | 4 | """
-=Mega Project List=-
5. Count Words in a String - Counts the number of individual words in a string.
For added complexity read these strings in from a text file and generate a
summary.
"""
import os.path
def count_words(string):
words = string.split()
return len(words)
def main(file):
filename = os.path.abspath(file)
with open(filename, 'r') as f:
count = [count_words(line) for line in f]
for i, v in enumerate(count):
print "Line %d has %d words in it." % (i+1, v)
if __name__ == '__main__':
main('footext.txt')
|
f5f862e7bc7179f1e9831fe65d20d4513106e764 | AhmedMohamedEid/Python_For_Everybody | /Data_Stracture/ex_10.02/ex_10.02.py | 1,079 | 4.125 | 4 | # 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
# Use the file name mbox-short.txt as the file name
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
hour = dict()
for line in handle:
line.rstrip()
if not line.startswith('From '): continue
words = line.split()
hour[words[5]] = hour.get(words[5] , 0 ) + 1
#print (hour)
hour2 = dict()
for key in hour.keys():
key.split(":")
hour2[key[0:2]] = hour2.get(key[0:2],0)+1
#print (hour2)
lst = []
for a,b in hour2.items():
lst.append((a,b))
lst.sort()
for a,b in lst:
print (a,b)
# ############# OutPut ==
# 04 3
# 06 1
# 07 1
# 09 2
# 10 3
# 11 6
# 14 1
# 15 2
# 16 4
# 17 2
# 18 1
# 19 1
|
157e068c703abe7111b4056c2f66f1954295b465 | michael-creator/passlocker | /user_test.py | 916 | 3.515625 | 4 | import unittest
from user import User
class TestUser(unittest.TestCase):
"""
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase:TestCase that help in creating test cases
"""
def setUp(self):
"""
set up method to run before each test cases.
"""
def test_init(self):
"""
checks to test if the object is initialized properly
"""
def test_save_object(self):
"""
checks wether object is saved corectly
"""
def tearDown(self):
"""
tearDown method that does clear up after test case has run.
"""
User.user_list = []
def test_delete_user(self):
"""
test_delete_user to test if we can remove a user from the user list
"""
if __name__ == '__main__':
unittest.main() |
14fd0afadadb85ccffb9e5cb447fa155874479ea | thienkyo/pycoding | /quick_tut/basic_oop.py | 657 | 4.46875 | 4 | class Animal(object):
"""
This is the animal class, an abstract one.
"""
def __init__(self, name):
self.name = name
def talk(self):
print(self.name)
a = Animal('What is sound of Animal?')
a.talk() # What is sound of Animal?
class Cat(Animal):
def talk(self):
print('I\'m a real one,', self.name)
c = Cat('Meow')
c.talk() # I'm a real one, Meow
# Compare 2 variables reference to a same object
a = [1, 2, 3]
b = a
print(b is a) # True
# Check if 2 variables hold same values
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False
print(a == b) # True
# None is an Object
print(None is None) # True
|
9998ed498be655134489021bdbf26f1545003344 | mrgomides/VemPython | /desafios/exe032.py | 668 | 3.703125 | 4 | # Projeto: VemPython/exe032
# Autor: rafael
# Data: 15/03/18 - 15:13
# Objetivo: TODO Faça um programa que leia um ano qualquer e mostre se é BISSEXTO
from datetime import date
print("ANO BISSEXTO?")
ano = int(input('Informe o ano. Ou coloque 0: '))
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print('Ano Bissexto: {}'.format(ano))
else:
print('Ano Normal: {}'.format(ano))
# PORRA PROFESSOR!
#if pm == 0:
# if sm == 0:
# if tm == 0:
# print('Ano Bissexto')
# else:
# print('Ano normal')
# else:
# print('Ano Bisexto')
#else:
# print('Ano normal')
|
bd0d03232a43888152bf81a7c7c2f61f8caae1a8 | mrgomides/VemPython | /desafios/exe005.py | 282 | 3.875 | 4 | # Projeto: VemPython/exe005
# Autor: rafael
# Data: 13/03/18 - 16:49
# Objetivo: TODO Faça um programa que leia um numero Inteiro e mostre na tela o seu sucessor e seu antecessor
n1 = int(input('Informe um numero: '))
print('O Sucessor: {} \nO Antecessor: {}'.format(n1+1, n1-1))
|
35e57d91f500b329a988628b25fa779c7bd0e7d8 | mrgomides/VemPython | /desafios/exe025.py | 291 | 3.78125 | 4 | # Projeto: VemPython/exe025
# Autor: rafael
# Data: 14/03/18 - 16:54
# Objetivo: TODO Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome
nome = str(input('Informe um Nome: '))
print('É verdadeiro que tem Silva no seu nome? {}'.format('silva' in nome.lower())) |
ac1be3a81e9f6303f98fc6ef8082334bc330566c | mrgomides/VemPython | /desafios/exe038.py | 579 | 3.78125 | 4 | # Projeto: VemPython/exe038
# Autor: rafael
# Data: 16/03/18 - 10:43
# Objetivo: TODO Escreva um programa que leia dois numeros inteiros e compare-os. Mostrando na tela
# uma mensagem:
# - O primeiro valor é maior
# - O segundo valor é maior
# - Não existe valor maior os dois são iguais
vl1 = int(input('Informe um número Inteiro: '))
vl2 = int(input('Informe outro número Inteiro: '))
if vl1 > vl2:
print('{} é maior que {}'.format(vl1, vl2))
elif vl2 > vl1:
print('{} é maior que {}'.format(vl2, vl1))
else:
print('{} e {} são iguais'.format(vl1, vl2))
|
cf452bedeaf4ec273dbde9c9e42495f46784d70a | mrgomides/VemPython | /desafios/exe053.py | 375 | 3.78125 | 4 | # Projeto: VemPython/exe053
# Autor: rafael
# Data: 16/03/18 - 17:29
# Objetivo: TODO Crie um programa que leia uma frase qualquer e diga se ela é um palindramo, desconsiderando os espaços
frase = str(input('Informe a frase: '))
fraseTest = frase.strip().replace(" ", "").upper()
if fraseTest == fraseTest[::-1]:
print('A Frase: {}\nÉ um polindramo!'.format(frase)) |
55ba2059f6e142bac530ba83e5664b0a18e742f7 | mrgomides/VemPython | /desafios/exe020.py | 515 | 3.765625 | 4 | # Projeto: VemPython/exe020
# Autor: rafael
# Data: 14/03/18 - 11:37
# Objetivo: TODO O mesmo professor do desafio anterior quer a ordem de apresentação de trabalhos dos
# quatro alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada
from random import shuffle
alunos = []
for cont in range(0, 4):
alunos.append(str(input('Informe o nome do aluno {}: '.format(cont+1))))
shuffle(alunos)
for cont in range(0, 4):
print('O {}º aluno é: {}'.format(cont+1, alunos[cont]))
|
c1a1b557554355308cc2df2ac26c2d9375e6fb05 | mrgomides/VemPython | /desafios/exe031.py | 586 | 3.953125 | 4 | # Projeto: VemPython/exe031
# Autor: rafael
# Data: 15/03/18 - 15:02
# Objetivo: TODO Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem.
# Cobrando R$ 0,50 por Km para viagens de até 200Km e R$ 0,45 para viagens mais longas
print('BUSÃO DA LOUCURA\n')
km = float(input('Informe a distância da viagem: Km '))
if km > 200:
print('ETA QUE EU TÔ NO DE VOLTA PRA MINHA TERRA!')
print('O valor da sua Viagem: R$ {}'.format(km*0.45))
else:
print('Chama um Uber Poxa!')
print('O Valor da sua viagem: R$ {}'.format(km*0.5))
|
ea81459cf57703d3a7e17a2532fbe7a7a52e719d | wilsonwagn/FlappyBirdMinaj | /Flappy Bird Minaj (Python)/ots/itens.py | 628 | 3.640625 | 4 | import pygame
"""
Variavéis padrões:
x x y = Altura x Largura.
w x h = Altura x Largura
"""
class itens:
def __init__(self, win, x, y, w, h, img, r):
self.x = x
self.y = y
self.w = w
self.h = h
self.r = r #Rotação
self.visivel = True
self.img = img #Imagem
self.win = win #Janela
def show(self):
#Função para mostrar os objetos:
imagem = pygame.transform.rotate(self.img, self.r)
if self.visivel:
#Se estiver visivel, mostra a imagem na posição X x Y!
self.win.blit(imagem, (self.x, self.y))
|
da3e793f2542785087ef540e776f97035b408f62 | seru1us/hackernoon-projects | /Mean, Var, and Std.py | 5,047 | 4.5 | 4 | import numpy
#my_array = numpy.array([ [1, 2], [3, 4] ])
# print("MEANS!")
# print(numpy.mean(my_array, axis = 0)) #Output : [ 2. 3.]
# print(numpy.mean(my_array, axis = 1)) #Output : [ 1.5 3.5]
# # print(numpy.mean(my_array, axis = 2)) # When I add this to the sample code, I get a tuple index out of range
# print(numpy.mean(my_array, axis = None)) #Output : 2.5
# print(numpy.mean(my_array)) #Output : 2.5
# Oooooo kkkkkk. So I'm re-learning a lot of statistics stuff here with this Stats 001 course.
# Here are some interesting notes from my google rabbit hole that is Means/Axis/etc:
# Flattening an array: if passing a multi-dimensional array (like the one above) then the numpy
# mean will flatten it. In other words, flattening this:
# [ [1, 2], [3, 4], [3, 3] ]
# Should become this:
# [ 1, 2, 3, 4, 3, 3 ]
# Now for Axis. The "axis" parameter noted here:
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
# means something that I either don't remember or have never heard. Everyone's talking about "axis this" and "axis that"
# and I couldn't seem to find a valid definition
# SO while I foray once more into something that feels like it's high school statistics, this is what "axis" means:
# Given the following numpy array:
# numpy.array([ [1, 2], [3, 4], [3, 3] ])
# AXIS refers to the nth element in each multidemensional array. For example.
# numpy.mean(my_array, axis = 0)
# will process on the quoted values:
# [ ["1", 2], ["3", 4], ["3", 3] ]
# and...
# numpy.mean(my_array, axis = 1)
# will process on the quoted values:
# [ [1, "2"], [3, "4"], [3, "3"] ]
# etc.
# The important thing to remember here is without specifying the axis, mean flattens the entire tuple.
# MOVING ONNNNNNNN TO VARIANCES
# print("VARIANCES!")
# print(numpy.var(my_array, axis = 0)) #Output : [ 1. 1.]
# print(numpy.var(my_array, axis = 1)) #Output : [ 0.25 0.25]
# print(numpy.var(my_array, axis = None)) #Output : 1.25
# print(numpy.var(my_array)) #Output : 1.25
# Welp, here we go back to children's web sites explaining stats concepts.
# A varienace is defined as:
# The average of the squared differences from the Mean.
# https://www.mathsisfun.com/data/standard-deviation.html
# Let's use our example with default paramters, which would flatten this and use:
# [ 1, 2, 3, 4 ]
# Essentially you:
# 1) Work out the mean.
# ( 1 + 2 + 3 + 4 ) / 4 = 2.5
# 2) For each number: subtract the Mean and square the result.
# ( 1 - 2.5 )^2 = -2.25, ( 2 - 2.5 )^2 = -0.25, ( 3 - 2.5 ) = 0.25, ( 4 - 2.5 ) = 2.25
# 3) Then work out the average of those squared differences.
# ( -2.25 + -0.25 + 0.25 + 2.25 ) / 4 = 0
# In retrospect I chose an awful example because the variance is zero.
# That was fun. Now for Standard Deviation.
# print("STANDARD DEVIATIONS!")
# print(numpy.std(my_array, axis = 0)) #Output : [ 1. 1.]
# print(numpy.std(my_array, axis = 1)) #Output : [ 0.5 0.5]
# print(numpy.std(my_array, axis = None)) #Output : 1.11803398875
# print(numpy.std(my_array)) #Output : 1.11803398875
# Super easy. Just the root of the variance. Neato.
# After stuggling a bit more with what a multidimensional array IS and how it is DEFINED, this helped a lot:
# https://www.mathworks.com/help/matlab/math/multidimensional-arrays.html
# Now let's, uh... get to the excersise.
import numpy
# see below for my frustrations for why this is necessary, and I thought
# it was a dtype problem.
numpy.set_printoptions(legacy='1.13')
def inputToIntArray(entry):
entry = entry.split(" ")
return list(map(int, entry))
# Just
rayTable = inputToIntArray(input())
# Initialize the empty numpy array according to the first entry.
# Something is wrong here. When I input this in and run it, the
# online compiler rounds to the 12th mantissa... which is super wierd
# considering float32 comes out too long and float16 is far too short.
# the result it: 11803398875 where my code spits out: 118033988749895
finalArray = numpy.zeros(rayTable)
# I can't help but think that there is a better way to keep
# prompting until the input is done... but let's see whats up
for i in range(rayTable[0]):
entry = inputToIntArray(input())
# I spent a whole day trying to get the below to work, only to
# discover that I could just...
#finalArray = numpy.append([finalArray], entry, axis=i)
finalArray[i] = entry
print(numpy.mean(finalArray, axis = 1))
print(numpy.var(finalArray, axis = 0))
print(numpy.std(finalArray))
# It should be noted here that someone else on HR got the following to work:
# n,m = map(int, input().split())
# b = []
# for i in range(n):
# a = list(map(int, input().split()))
# b.append(a)
# b = np.array(b)
# Which wrinkles my brain a bit. They added a numpy array to a normal one- looks like I
# need to play around with this some more. I think maybe I was going a bit too
# hard in the numpy world when simpler answers would have worked. |
c6155ca957544e00f08f66f4dc3e8e4b2744c20f | ArronYR/Machine-Learning-Code | /learning_demo_02.py | 536 | 3.625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
from numpy.linalg import inv
from numpy import dot
from numpy import mat
# y = 2x
X = mat([1, 2, 3]).reshape(3, 1)
Y = 2 * X
# 最小二乘法
# theta = (X'X)^-1X'Y
theta = dot(dot(inv(dot(X.T, X)), X.T), Y)
# 梯度下降法
# theta = theta - alpha*(theta*X-Y)*X
theta = 1.
alpha = 0.1
for i in range(100):
theta = theta + alpha * np.sum((Y - dot(X, theta))
* X.reshape(1, 3)) / len(X)
# np.sum 对矩阵加权平均
print(theta)
|
df3c5db72ccb697322f83a56606456580b549ed5 | anoopyadav/DataScienceFromScratch | /LinearAlgebra/statistics.py | 2,813 | 4.03125 | 4 | from collections import Counter
from random import randint
from matplotlib import pyplot as plt
from LinearAlgebra.vectors import sum_of_squares, dot
from math import sqrt
num_friends = [randint(1, 101) for x in range(200)]
friend_counts = Counter(num_friends)
""" Plot the friend-count vs number of people
"""
x_axis = range(101)
y_axis = [friend_counts[x] for x in x_axis]
plt.bar(x_axis, y_axis)
plt.axis([0, 101, 0, 25])
plt.title("Histogram of friend counts")
plt.xlabel('Number of friends')
plt.ylabel('Number of people')
plt.show()
""" Get some statistics going
"""
num_points = len(num_friends)
largest_value = max(num_friends)
smallest_value = min(num_friends)
""" Basic statistics methods
"""
def mean(x):
return sum(x) / len(x)
def median(v):
length = len(v)
sorted_v = sorted(v)
midpoint = length // 2
if length % 2 is not 0:
return sorted_v[midpoint]
else:
low = midpoint - 1
high = midpoint
return (sorted_v[low] + sorted_v[high]) / 2
def quantile(x, p):
index = int(p * len(x))
return sorted(x)[index]
def mode(x):
""" Returns a list of most common values """
counts = Counter(x)
max_count = max(counts.values())
return [x for x, count in counts.items()
if count == max_count]
print("Mean: " + str(mean(num_friends)))
print("Median: " + str(median(num_friends)))
print("Mode: " + str(mode(num_friends)))
""" The following methods calculate the Variance and the Standard Deviation for a set of values"""
def de_mean(x):
x_bar = mean(x)
return [x_i - x_bar for x_i in x]
def variance(x):
n = len(x)
deviations = de_mean(x)
return sum_of_squares(deviations) / (n - 1)
def standard_deviation(x):
return sqrt(variance(x))
print("Standard Deviation: " + str(standard_deviation(num_friends)))
def interquantile_range(x):
""" Return the difference between the 75th persentile and 25th percentile of a dataset """
return quantile(x, 0.75) - quantile(x, 0.25)
print("Interquantile range: " + str(interquantile_range(num_friends)))
""" Methods to determine correlation
"""
def covariance(x, y):
""" +ve value : X is large when Y is large
-ve value: X is small when Y is small
Hard to interpret units since they're the product of the two datasets
"""
n = len(x)
return dot(de_mean(x), de_mean(y)) / (n - 1)
def correlation(x, y):
""" Correlation is unitless, so more meaningful"""
stddev_x = standard_deviation(x)
stddev_y = standard_deviation(y)
if stddev_x > 0 and stddev_y > 0:
return covariance(x, y) / stddev_x / stddev_y
else:
return 0
daily_minutes = [randint(1, 30) for x in range(len(num_friends))]
print("Correlation: " + str(correlation(num_friends, daily_minutes)))
|
e7106abd83be9b0bde7758fb4b6494f331abfb9d | aiologybay/TransferLearning | /transferLearning.py | 1,081 | 3.65625 | 4 | import torch
import torchvision
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
x=torch.randn(10,1)
y=2*x+3
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.linear1=nn.Linear(1,3)
self.linear2=nn.Linear(3,1)
def forward(self,x):
x=self.linear1(x)
x=self.linear2(x)
return x
net=Net()
print(net)
for param in net.parameters():
print(param)
print('================================')
for param in net.linear1.parameters():
print(param)
param.requires_grad=False
print('================================')
for name,param in net.named_parameters():
print(name,'\n',param)
criterion=torch.nn.MSELoss()
optimizer=torch.optim.SGD(net.parameters(),lr=1e-2,momentum=0.9)
for i in range(1000):
y_pred=net(x)
loss=criterion(y_pred,y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
#print('loss:{:.6f}'.format(loss.item()))
print('================================')
for name,param in net.named_parameters():
print(name,'\n',param)
|
45196a57b8eac8fa13d01ea7a7697cf1b03fba4a | bonbonnie/ToOffer | /8字符串转整数.py | 708 | 3.84375 | 4 | '''
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
'''
class Solutions(object):
def StrToInt(self, s):
if s == '':
return 0
res = 0
pos = 1
for i in s:
if i == '+' or i == '-':
if s.index(i) == 0:
pos = -1 if i == '-' else 1
else:
return 0
elif '0' <= i <= '9':
res = res*10 + int(i)
else:
return 0
return pos*res if res else 0
if __name__ == "__main__":
print(Solutions().StrToInt('-78'))
|
00f9d933e019f7f6038823082e21308b4844e664 | bonbonnie/ToOffer | /9平衡二叉树.py | 881 | 3.71875 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def Treeheight(self, pRoot):
if pRoot == None:
return 0
if pRoot.left == None and pRoot.right == None:
return 1
lh = self.Treeheight(pRoot.left)
rh = self.Treeheight(pRoot.right)
return max(rh, lh) + 1
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot == None:
return True
return abs(self.Treeheight(pRoot.left) - self.Treeheight(pRoot.right)) <= 1
if __name__ == "__main__":
root = TreeNode(3)
root.left, root.right = TreeNode(9), TreeNode(20)
root.left.left, root.right.right = TreeNode(15), TreeNode(7)
root.left.left.left = TreeNode(3)
print(Solution().IsBalanced_Solution(root))
|
a75f5b32953b00d9366aa170454cb932cf4e7d8b | bonbonnie/ToOffer | /7变态跳台阶.py | 297 | 3.875 | 4 | class Solutions(object):
def oddJumpFloor(self, n):
if n == 1 or n == 2:
return n
res = psum = 3
for i in range(n - 2):
res = psum + 1
psum += res
return res
if __name__ == "__main__":
print(Solutions().oddJumpFloor(5)) |
641771afc19c1e9b9932fac893c74ca4d3541276 | emil904/CodeAcademyPython | /sumOfDigits.py | 91 | 3.546875 | 4 | def digit_sum(n, s=0):
l = str(n)
for x in l:
s += int(x)
return s
|
d2a163f00abb3166aee84001cc5784aa55fee5e6 | arunkumaarr/myfirstproject | /guessgame.py | 408 | 3.96875 | 4 | from random import randint
num = randint(1, 10)
print("Hey i am thinking of a number bet 1 to 10 can you guess :P")
print('your are left with three chances !!!!')
i=3
while i > 0:
i -=1
user_guess1 = int(input('Enter your number Guess1'))
if user_guess1== num:
print('you guessed it right')
break
else:
print('Suit up you !!! :)you are left with %d more tries' %(i)) |
c5138974f25a246029fa5f7af300cfc2c3ee3fe3 | arunkumaarr/myfirstproject | /animalcracker.py | 234 | 3.515625 | 4 | def animal_crackers(text):
word=text.split( )
print(word)
for i in word:
if (i[0][0] == i[1][0]):
return True
else:
return False
string = 'levalheaded llama'
animal_crackers(string) |
2aafcef675b26ab1591c22272d868ac4e9743fbd | arunkumaarr/myfirstproject | /codewar3.py | 161 | 3.890625 | 4 | def longest(s1, s2):
s1 += s2
x=set(s1)
s1=list(x)
s1.sort()
#s1.remove()
return s1
k=longest("aretheyhere", "yestheyarehere")
print(k) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.