blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0b1adfa9f65f769f0cba3d76d315d8f1dfbd7c1c | XYangL/CodeJam | /visitTree_ Iterative.py | 1,749 | 4.09375 | 4 | from TreeNode import TreeNode
# http://www.gocalf.com/blog/traversing-binary-tree.html
# Using iterative/loop to traverse tree in pre/in/post order
# need a STACK to store the visited but not printed nodes
def visitTree_Iterative(root, order):
re = []
if order == 'NLR':
# init a stack with root
# use a while loop if stack!=NONE
# in the loop, pop and print first and then push RIGHT & LEFT
stack = [root]
while len(stack) != 0:
temp = stack.pop()
re.append(temp.val)
if temp.right != None:
stack.append(temp.right)
if temp.left != None:
stack.append(temp.left)
elif order == 'LNR':
# init a stack, and
# using a while loop if root!=NONE or stack!=NONE, in the loop,
# update root to the most left node, and push the passed nodes
# if no left more, pop from the stack (#!no left or left has been handled!#),
# and print its val
# then update root to the right
stack = []
while root!= None or len(stack)!=0:
if root != None:
stack.append(root)
root = root.left
else:
root = stack.pop() # poped is no left or left has been handled
re.append(root.val)
root = root.right
elif order =='LRN':
# after handle all left children or after handle all right children
# BOTH will make self = stack.pop()
stack = []
pre = None
while root!=None or len(stack)!=0:
if root != None:
stack.append(root)
root = root.left
elif stack[-1].right!=pre:# poped is no left or left has been handled
root = stack[-1].right
pre = None
else:
pre = stack.pop()
re.append(pre.val)
return re
demo = TreeNode(0)
demo.setDemo()
order = ['NLR','LNR','LRN']
for i in order:
print i,' : ',
for ch in visitTree_Iterative(demo,i):
print ch,
print |
d4020ee668ea0b58fa993905662b6ebf65f97a4b | JZ1015/NetworkBandwidthMonitor | /animation.py | 994 | 3.5 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ani
fig=plt.figure()
def animate(i):
data=open('monitor.txt','r').read() #file reader
dataArray=data.split('\n') #data manipulation, split
DateTime=[] #data structure list
sent=[]
rev=[]
for record in dataArray: #for loop
if len(record)>2: #if condition
d,s,r=record.split(',')
DateTime.append(pd.to_datetime(d)) #queue
sent.append(int(s))
rev.append(int(r))
if len(DateTime)>20:
DateTime.pop(0)
sent.pop(0)
rev.pop(0)
fig.clear()
plt.title("Network Bandwidth Monitor")
plt.xlabel('DateTime')
plt.ylabel('KB Sent/Reveived')
plt.plot(DateTime,sent,label='KB Sent')
plt.plot(DateTime,rev,label='KB Received')
plt.legend()
plt.xticks(rotation=80)
animation=ani.FuncAnimation(fig,animate,interval=2000)
plt.show()
|
921416a4189a9d91235e3627cba1c58962bf3f04 | muhammadhasan01/cp | /Online Judge/TLX/Pemrograman Dasar/5 - If Then Multi.py | 52 | 3.65625 | 4 | a = int(input())
if a > 0 and a%2 == 0:
print(a) |
bee2e28bd51ee3f7b0390071885856b7ea9801c4 | feladie/D04 | /HW04_ch08_ex05.py | 776 | 4.3125 | 4 | # Structure this script entirely on your own.
# See Chapter 8: Strings Exercise 5 for the task.
# Please do provide function calls that test/demonstrate your
# function.
'''Returns the word with each of its characters rotated n times.'''
def rotate_word(word, n):
result = '' # Result string
for letter in word:
new_letter_num = ord(letter) + n
if letter.islower():
if new_letter_num < 97:
new_letter_num = 123 - (97 - new_letter_num)
result += chr(new_letter_num)
else:
if new_letter_num < 64:
new_letter_num = 91 - (65 - new_letter_num)
result += chr(new_letter_num)
return result
def main():
rotate_word('Python', 1)
rotate_word('cheer', 7)
rotate_word('melon', -10)
rotate_word('MELON', -10)
if __name__ == '__main__':
main() |
cdfc3b709c47a12f60a4a2b221e16b0e8b60d6d3 | Kamilla23072001/Lab1 | /7.4.py | 402 | 3.546875 | 4 | import random
num = random.randint(1,10)
while True:
tryes = int(input('Введите число:'))
if tryes == num:
print('Победа')
break
else:
print('Повторите еще раз')
"""Прогрмма загадывает случайное число лт 1 до 10 и дает пользователю его отгадать"""
|
13d1c9228ee1b4412d77e0c517b5977dd7cf79eb | adamrodger/google-foobar | /3-3.py | 837 | 3.796875 | 4 | # Sources:
# https://en.wikipedia.org/wiki/Partition_(number_theory)
# https://en.wikipedia.org/wiki/Partition_function_(number_theory)
# https://math.stackexchange.com/questions/146482/the-number-of-ways-to-write-a-positive-integer-as-the-sum-of-distinct-parts-with
# http://mathworld.wolfram.com/PartitionFunctionQ.html
# https://math.stackexchange.com/questions/1971870/partitions-into-at-least-two-distinct-parts
def solution(n):
a = [0] * (n+1)
a[0] = 1
a[1] = 1
# sum the partial products up to n
for x in range(2, n + 1):
for k in range(n, x - 1, -1):
a[k] = a[k] + a[k-x]
# -1 because this will include a 1-length partition which we don't want
return a[n] - 1
if __name__ == "__main__":
print solution(1)
print solution(2)
print solution(5)
print solution(200)
|
91d0958fea51e05903e8dd4db09a71200e980d2f | sacsachin/programing | /insertion_sort_list.py | 1,590 | 3.953125 | 4 | # !/usr/bin/python3
"""
https://leetcode.com/problems/insertion-sort-list/
Insertion sort list.
"""
class Node:
def __init__(self, val=0, nxt=None):
self.val = val
self.next = nxt
class LinkList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(val=nodes.pop(0))
self.head = node
for elem in nodes:
node.next = Node(val=elem)
node = node.next
def display(head):
while head:
print(head.val, end=" ")
head = head.next
print(end="\n")
def lis(head):
lis = []
while head:
lis.append(head.val)
head = head.next
return lis[::]
def solve(head):
current = head
prev_current = None
while current:
mi = Node(float("inf"))
point = current
prev = point_prev = None
while point:
if point.val < mi.val:
mi = point
point_prev = prev
prev = point
point = point.next
if point_prev:
point_prev.next = mi.next
if current != mi:
if prev_current:
prev_current.next = mi
mi.next = current
else:
head = mi
mi.next = current
prev_current = mi
else:
prev_current = current
current = current.next
return lis(head)[::]
if __name__ == "__main__":
ll = LinkList([(lambda x: int(x))(x) for x in input().split()])
print(solve(ll.head))
|
aef93a17fbff81e0a74436c2f1ba3a054261fec1 | ramchinta/Algorithms | /RandomizedSelect.py | 1,510 | 3.640625 | 4 | def partition(unsorted_array,first_index,last_index):
if first_index == last_index:
return first_index
pivot = unsorted_array[first_index]
pivot_index = first_index
index_of_last_element= last_index
less_than_pivot_index = index_of_last_element
greater_than_pivot_index = first_index + 1
while True:
while unsorted_array[greater_than_pivot_index] < pivot and greater_than_pivot_index < last_index :
greater_than_pivot_index = greater_than_pivot_index + 1
while unsorted_array[less_than_pivot_index] > pivot and less_than_pivot_index >= first_index:
less_than_pivot_index = less_than_pivot_index - 1
if greater_than_pivot_index < less_than_pivot_index:
temp = unsorted_array[greater_than_pivot_index]
unsorted_array[greater_than_pivot_index] = unsorted_array[less_than_pivot_index]
unsorted_array[less_than_pivot_index] =temp
else:
break
unsorted_array[pivot_index] = unsorted_array[less_than_pivot_index]
unsorted_array[less_than_pivot_index] = pivot
return less_than_pivot_index
def quick_select(array_list,left,right,k):
split = partition(array_list,left,right)
if split == k:
return array_list[split]
elif split < k:
return quick_select(array_list,split + 1,right,k)
else:
return quick_select(array_list,left,split - 1,k)
print(quick_select([25,45,35,14,351,144,22,1,4,5,6,44,14,78,5,441,6,87],0,17,12))
#45 |
db73169228d9d32a39dcc301c936baf85b9437e3 | stevalang/Data-Science-Lessons | /statistics/clt.py | 1,157 | 3.671875 | 4 | import random
import matplotlib.pyplot as plt
import numpy as np
import statistics as stats
# Create a normal distribution with mu = 5, sd = 2, n = 1000
pop_norm = np.random.normal(5, 2, 10)
# Plot frequency histogram
plt.hist(pop_norm, bins=20)
# plt.show()
def subsample_mean(data, n = 50):
'''
Creates and returns a subsample of a dataset, of a given size.
Parameters
----------
data: list-like
A list of samples of any numeric type
n: int
The size of the desired subsample
Returns
-------
mean_: float
The mean of the randomly chosen subsamples
'''
sample = []
while len(sample) < n:
idx = random.choice(range(len(data)))
sample.append(data[idx])
return stats.mean(sample)
means = [subsample_mean(data=pop_norm, n=50) for _ in range(1000)]
plt.hist(means, bins=20)
# plt.show()
# Assume prevoius imports are still available, create uniform distribution
pop_uni = np.random.uniform(0, 10, 1000)
plt.hist(pop_uni, bins=10)
# plt.show()
means = [subsample_mean(data=pop_uni, n=50) for _ in range(1000)]
plt.hist(means, bins=20)
# plt.show() |
6fc831ec6e9516fedfc7d645e1b2c7e949800c06 | dacioromero/hackerrank | /Python/np-dot-and-cross.py | 212 | 3.640625 | 4 | import numpy
def main():
N = int(input())
A, B = [numpy.array([list(map(int, input().split())) for _ in range(N)]) for _ in range(2)]
print(numpy.matmul(A, B))
if __name__ == '__main__':
main()
|
a9e6539b223163844a7004ef35b80236cefd7f43 | sang-woon/infrean_python1 | /section7-1.py | 1,747 | 3.90625 | 4 | # ------------------------------
# State Design Pattern
# ------------------------------
# Allow an object to alter its behavior when its internal state changes.
# The object will appear to change its class.
# https://github.com/rajan2275/Python-Design-Patterns/blob/master/Behavioral/state.py
from _ast import expr
from abc import ABC
class State(ABC):
def handle_state(self):
pass
class StateA(State):
def handle_state(self):
print('State changed to StateA.')
class StateB(State):
def handle_state(self):
print('State changed to StateB.')
class StateC(State):
def handle_state(self):
print('State changed to StateC.')
class Context(State):
def __init__(self):
self.state = None
def set_state(self, state):
self.state = state
def handle_state(self):
self.state.handle_state()
context = Context()
stateA = StateA()
context.set_state(stateA)
context.handle_state()
print('-------------------------------------')
stateB = StateB()
context.set_state(stateB)
context.handle_state()
print('-------------------------------------')
a = [1, 2, 3]
a = [1, 2, 3]
while True:
print()
while a:
while True:
a
for z in a:
print(z)
{'a': 5, 'b': 5}
def foo(a, b):
"""
:param a: 나이
:param b: 성별
"""
foo(b, 6)
b = [1, 2, 3]
c = {4, 5, 6}
'''
class $class$($object$):
"""$cls_doc$"""
def __init__(self,$args$):
"""Constructor for $class$"""
$END$
'''
'''
print($contents$)
$END$
'''
for i in b:
print(i)
print(test)
print(11111)
print(test)
prtt
print()
print()
prt
class testclass(object):
"""dkfjkdjfkjdf"""
def __init__(self,):
"""Constructor for testclass"""
|
e54069ffcdbe5853e0fb43bf655bcc9737047914 | sknaht/algorithm | /python/list/LRU.py | 1,646 | 3.5 | 4 | class LRUNode:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
self.prev = None
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.head = LRUNode(0, 0)
self.tail = LRUNode(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
self.count = 0
self.content = {}
def move2head(self, node):
prev, next = node.prev, node.next
prev.next = next
next.prev = prev
self.head.next.prev = node
node.next = self.head.next
node.prev = self.head
self.head.next = node
# @return an integer
def get(self, key):
if key in self.content:
t = self.content[key]
self.move2head(t)
return t.val
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
if key in self.content:
self.content[key].val = value
self.move2head(self.content[key])
return
if self.count >= self.capacity:
t = self.tail.prev
t.next.prev = t.prev
t.prev.next = t.next
self.count -= 1
del self.content[t.key]
t = LRUNode(key, value)
self.head.next.prev = t
t.next = self.head.next
t.prev = self.head
self.head.next = t
self.count += 1
self.content[key] = t
t = LRUCache(1)
t.set(2,1)
print t.get(2)
t.set(3,2)
print t.get(2)
print t.get(3)
|
4a0c600d1b632e384eaa8e2d9fabf5026c40d95b | xlax007/Collection-of-Algorithms | /Binary_search.py | 1,745 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 23:55:19 2020
@author: alexi
"""
def binary_search(array, target):
L = 0
R = len(array)-1
while L <= R:
mid = L + int((R-L)/2)
if array[mid] == target:
return (target,'at position:',mid)
if array[mid] < target:
L = mid + 1
else:
R = mid - 1
return -1
array = [0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,5,5,5,5,5,5,6,6,6,6,7,7,7,8,8,8,8,9,9,9,9,10,10,1512]
binary_search(array, 0)
#binary search, find a target that is >= than target
def binary_search_2(array, target):
L = 0
R = len(array)-1
ans = -1
while L <= R:
mid = L + int(((R-L)/2))
if array[mid] == target:
return array[mid], mid
elif array[mid] >= target:
ans = mid
R = mid - 1
else:
L = mid + 1
return array[ans], ans
array2 = [1,2,3,4,5,7,8,9,10,11,12,13,14,15,19]
binary_search_2(array2, 20)
#binary search, find maximum in a increasing-decreasing array
def binary_search_3(array):
L = 0
R = len(array)-1
ans = -1
while L <= R:
mid = L + int((R-L)/2)
if mid == 0:
if array[mid] > ans:
ans = array[mid]
L = mid+1
elif (mid-1) >=0:
if array[mid] > array[mid-1]:
ans = array[mid]
L = mid+1
else:
R = mid -1
return ans
array =[1,2,3,4,5,6,7,8,4,3,2,1]
binary_search_3(array)
|
cc8477c277c213f869db9fb13365b9b5a6d39d9d | wa57/info108 | /Lab3/exercise4.py | 439 | 4.21875 | 4 | if 0:
print('0 is true')
else:
print('0 is false')
print()
if 1:
print('1 is true')
else:
print('1 is false')
print()
if -1:
print('-1 is true')
else:
print('-1 is false')
extra = 2
if extra < 0:
print('small')
else:
if extra == 0:
print('medium')
else:
print('large')
extra = 2
if extra < 0:
print('small')
elif(extra == 0):
print('medium')
else:
print('large')
|
7cb64312a4c5593b07eea98d4671615abb4d4ad1 | Aasthaengg/IBMdataset | /Python_codes/p00003/s526735685.py | 500 | 3.734375 | 4 | #-*-coding:utf-8-*-
def get_input():
for i in range(int(input())):
yield "".join(input())
if __name__ == "__main__":
array = list(get_input())
for i in range(len(array)):
a,b,c = array[i].split()
if int(a)**2 + int(b)**2 == int(c)**2:
print(u"YES")
elif int(c)**2 + int(a)**2 == int(b)**2:
print(u"YES")
elif int(b)**2 + int(c)**2 == int(a)**2:
print(u"YES")
else:
print(u"NO") |
111b41f412b6c512e29a20e77233dd0c9de7bb65 | Ge0dude/PythonCookbook3 | /Chapter1/1.7KeepingDictInOrder.py | 581 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 15 07:38:31 2017
@author: brendontucker
"""
from collections import OrderedDict
d = OrderedDict()
d['grok'] = 4
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
for key in d:
print(key, d[key])
'''is built through a doubly linked list. Keys are ordered via insertion
order. When a key is first inserted, it is placed at the end of the list,
subsequent reorganization doesn't alter this order. This form of storage
does create a larger amount of data, something like twice that of a typical
dictionary.''' |
8802df921be214d87f1a82947bace484d09ba095 | melobarros/30-Day-LeetCoding-Challenge | /Week-2/Day09-BackspaceStringCompare.py | 1,139 | 3.734375 | 4 | """
Day 9 - Backspace String Compare
Leetcode Easy Problem
Given two strings S and T, return if they are equal when both are typed
into empty text editors. # means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and '#' characters.
Follow up:
Can you solve it in O(N) time and O(1) space?
"""
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
return self.bSpace(S) == self.bSpace(T)
def bSpace(self, string):
sList = []
for char in string:
if char == '#':
if sList != []:
sList.pop()
else:
sList.append(char)
return sList
|
d67cfc77ff248830e3c163958919dc81052bddce | greedy0110/algorithm | /baekjoon/5052.py | 768 | 3.6875 | 4 | import sys
import collections
def input(): return sys.stdin.readline().strip()
class Tries:
def __init__(self):
self._next = {}
self._is_terminal = False
def insert(self, word):
if not word:
self._is_terminal = True
return not self._next
else:
key = word[0]
if key not in self._next:
self._next[key] = Tries()
return not self._next[key]._is_terminal and self._next[key].insert(word[1:])
t = int(input())
for _ in range(t):
tries = Tries()
n = int(input())
process = True
for _ in range(n):
word = input()
if process and not tries.insert(word):
process = False
print("YES" if process else "NO")
|
13059e2644c7b98c9f34a2818a8f2eef2cb0e60d | emreozgoz/KodlamaEgzersizleri | /if else/oyuncukayıt.py | 505 | 3.921875 | 4 | username = "emreozgoz"
passw= 123456
print("Hoşgeldiniz Lütfen Kullanıcı adınızı ve şifrenizi giriniz")
a = input("Kullanıcı adınızı giriniz")
b = int(input("Şifrenizi Giriniz "))
if (a!= username and b== passw):
print("Kullanıcı adınız hatalı")
if (a != username and b != passw):
print("Kullanıcı adı ve Parolanız hatalı")
if (a == username and b != passw):
print("Hatalı Şifre")
elif(a == username and b == passw):
print("Başarıyla giriş yaptınız") |
1512c5a3c194b873f0fbe54607e558597ee60798 | halysl/python_module_study_code | /src/study_checkio/even the last.py | 323 | 3.796875 | 4 | def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
sum = 0
try:
for i in array[::2]:
print(i)
sum += i
sum = sum * array[-1]
print(sum)
except:
return 0
array = [0, 1, 2, 3, 4, 5]
checkio(array) |
c44715669aa9563fcccba5086cf1061974dd0660 | prbarik/My_Py_Proj | /.vscode/pig_latin.py | 365 | 4 | 4 | # PIG LATIN
# If word starts with vowel, add 'ay' to the end
# If word does not start with vowel, then put first letter to the end and add 'ay'
def pig_latin(word):
first_letter = word[0]
if first_letter in 'aeiou':
pig_word = word + 'ay'
else:
pig_word = word[1:] + first_letter + 'ay'
return pig_word
print(pig_latin('goat'))
|
ba91f0c52364ad29b762eefb7d9d2f6b15b82c33 | Sixmillion/pycharm | /test/04.数据结构.py | 1,551 | 3.6875 | 4 | #字符串(不可变元素,'...')
a='py''thon'#可拼接
b='py'+'thon'
#列表(可变元素,[*,*,...])
list=['a']
ex_list=['c','d']
list.append('b')
list.extend(ex_list)
list.insert(len(list),'e')
list.remove('e')
list.pop(3)#删除并返回指定位置的值,缺省为最后一个元素
#list.clear()#清楚列表所有元素
list.index('b')#返回指定元素的索引
list.count('a')#返回出现次数
list.sort()
list.reverse()
print(list)
#lambda表达式(列表推导式:有表达式和for-if子句组成)
squares=[x**2 for x in range(0,6)]
two=[(x,y) for x in range(1,10) for y in range(1,10)
if x==2*y]
#例:矩阵的转置:将matrix的每个元素的第i个子元素重新作为第j行
matrix=[
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
]
transpose=[[row[i] for row in matrix]for i in range(4)]
del list[3]#可以通过索引的方式移除元素或删除列表变量
#元祖(不可变元素,但可包含可变元素,一般用()表示)
empty=()#0元素元祖
sigle='single',#1元素元祖
#集合(不重复元素组成的无序集合)
a=set('set',1)
b={'set',2}
c=set(list)#可以将列表作为参数
#字典(以关键字作为索引,数字、字符串、不可变序列可以作为关键字)
dict={'key':'value'}
temp=dict['key']#索引
keys=list(dict)
del dict['key']
dict1=dict([('a',4536),('b',4848),('e',236)])#从键值对序列创建
#数据结构循环技巧
#序列
for i,v in enumerate(['da','sdeas','defa']):
print(i,v)
#字典
for k,v in dict1.item():
print(k,v)
|
1144795851de8c5918ecac0d8b1ffd1e902061f4 | sphamv/mit-ocw-6.0001 | /ps1/ps1a.py | 750 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 15 00:41:29 2017
Finished: 02:19 AM
@author: Dev Jboy Flaga
"""
# Part A: House Hunting
annual_salary = float(input('Enter your annual salary: '))
portion_saved = float(input('Enter the percent of your salary to save, as a decimal: '))
monthly_savings = (annual_salary / 12) * portion_saved
total_cost = float(input('Enter the cost of your dream home: '))
portion_down_payment = 0.25 #25%
down_payment = total_cost * portion_down_payment
annual_return = 0.04
current_savings = 0.0
number_of_months = 0
while current_savings < down_payment:
current_savings += monthly_savings + ((current_savings * annual_return) / 12)
number_of_months += 1
print('Number of months: {}'.format(number_of_months)) |
d8e6ace169f556d2b335dfc8cfa9849469fb774d | aKryuchkova/programming_practice | /week03/exercise13.py | 799 | 4.1875 | 4 | '''
Нарисуйте смайлик с помощью написанных функций рисования круга и дуги.
'''
import turtle as t
def duga(n):
for i in range(180):
t.forward(n)
t.right(1)
def krug(n):
for i in range(360):
t.forward(n)
t.left(1)
t.color('yellow')
t.begin_fill()
krug(3)
t.end_fill()
t.penup()
t.left(90)
t.forward(250)
t.left(90)
t.forward(70)
t.pendown()
t.color('blue')
t.begin_fill()
krug(0.3)
t.end_fill()
t.penup()
t.right(180)
t.forward(140)
t.pendown()
t.right(180)
t.begin_fill()
krug(0.3)
t.end_fill()
t.color('black')
t.width(10)
t.penup()
t.forward(70)
t.left(90)
t.forward(70)
t.pendown()
t.forward(70)
t.penup()
t.left(90)
t.forward(60)
t.pendown()
t.right(90)
t.width(10)
t.color('red')
duga(1) |
ff633157875c84c869f5f23fa32b201f75d8f17b | AndreiAniukou/Python-s | /if_elif_else.py | 542 | 3.75 | 4 | '''
age = int(input('Enter ur age'))
if age <= 4:
print('ur ticket is free')
elif age <= 18:
print('ur ticket cost is 5$')
else:
print('ur ticket cost 10$')
'''
'''
age = int(input('Enter ur age!'))
if age <= 4:
price = 0
elif age <= 18:
price = 5
else:
price = 10
print('Ur ticket cost $' + str(price) + '.')
'''
age = int(input('Enter ur age!'))
if age <= 4:
price = 0
elif age <= 18:
price = 5
elif age <= 65:
price = 10
elif age >= 65:
price = 5
print('Ur ticket cost $' + str(price) + '.')
|
6642bfdc6d5b1014b5d674ad9d57c79783096950 | pyroRocket/Python | /Python101/Math.py | 389 | 4 | 4 | # Math
print("Math time: ")
print(67 + 69) # Add
print(67 - 69) # Subtract
print(67 * 69) # Multiply
print(10 / 5) # Divide
print(20 + 20 - 20 * 20 / 20) # PEMDAS (Order of operations)
print(20 ** 2) # Exponents (20 ^ 2)
print(23 % 4) # Modulo will return the remainder of a division operation
print(10 // 5) # truncated division, if there is a decimal it will be dropped
|
b116930b70f79fdae156095cb25bc3e2475fceb2 | Phillyclause89/ISO-8601_time_converter | /time_converter.py | 3,094 | 3.890625 | 4 | # iso_time must be a timestamp string in ISO 8601 format and offset is to change the timezone
def time_convert(iso_time, offset=0):
# months dict for converting from numerical month representation to name
months = {1: "January", 2: "February", 3: "March",
4: "April", 5: "May", 6: "June",
7: "July", 8: "August", 9: "September",
10: "October", 11: "November", 12: "December"}
# last_dy dict for getting the last day of a month
last_dy = {1: 31, 2: 28, 3: 31, 4: 30,
5: 31, 6: 30, 7: 31, 8: 31,
9: 30, 10: 31, 11: 30, 12: 31}
# Parse out the iso_time string and convert year, month, day and hour into integers. (keep minutes as a string)
yr = int(iso_time[0:4])
mo = int(iso_time[5:7])
dy = int(iso_time[8:10])
hr = int(iso_time[12:14])
mi = iso_time[15:17]
# Add the offset to hour to calculate new time zone time.
hr = hr + offset
# Check if the timestamp is in a leap year and update February's last day in the last_dy dict.
if yr % 4 == 0:
last_dy[2] = 29
# Check if adding the offset pushes the hour into the negative thus requiring the day be changed to the day before.
if hr < 0:
# If true we add 24 to our negative hour value to get our new hour value.
hr = 24 + hr
# Check if our timestamp for the 1st of a month
if dy == 1:
# If true we set the month to the month prior
mo = mo - 1
# Check if the month is Jan so that we can update the year if needed.
if mo < 1:
# If true, we set the moth to december, subtract 1 from the year and finally update the day.
mo = 12
yr = yr - 1
dy = last_dy[mo]
# If the year doesnt change we just update the day using the last day dict.
else:
dy = last_dy[mo]
# Check if adding the offset pushes the hour greater than 11pm thus requiring the day tobe changed to the day after.
elif hr > 23:
# If true we calculate our new hour by subtracting 24 from our hour value and add 1 to the day
hr = hr - 24
dy = dy + 1
# if our new day value is greater than the last day of the month we update our month value
if dy > last_dy[mo]:
mo = mo + 1
# If our month is greater than 12, we update our year, set the month to jan and finally set the day to 1.
if mo > 12:
mo = 1
yr = yr + 1
dy = 1
# Otherwise we just set the day to 1 if the year doesnt change.
else:
dy = 1
# reference our month dict to get our month name.
month = months[mo]
# Convert from 24hour time to AM/PM format.
if hr > 12:
hr = hr - 12
t = "PM"
elif hr == 0:
hr = 12
t = "AM"
else:
t = "AM"
# Finally return our new datetime as a string.
return month + " " + str(dy) + ", " + str(yr) + ", " + str(hr) + ":" + mi + " " + t
|
a2d75298b2a46e738665629ec32cd00b9eec3247 | LichAmnesia/LeetCode | /python/113.py | 1,081 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Author: Lich_Amnesia
# @Email: alwaysxiaop@gmail.com
# @Date: 2016-10-07 01:42:15
# @Last Modified time: 2016-10-07 02:02:26
# @FileName: 113.py
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if root is None:
return []
ans = []
def dfs(root, add, path):
if not root:
return
if root.left is None and root.right is None and add + root.val == sum:
path.append(root.val)
ans.append([x for x in path])
path.pop()
return
path.append(root.val)
dfs(root.left, add + root.val, path)
dfs(root.right, add + root.val, path)
path.pop()
dfs(root, 0, [])
return ans |
95524087dc3a9a6a1936f6e83796eb6ac49cac86 | Priyansi/pythonPrograms | /chessPieceCanCapture.py | 689 | 3.578125 | 4 | from chessCanMoveToPos import isPosInsideBoard, alphaToNum, pieceFunctions, king, queen, bishop, knight, rook
def pawnCapture(pos1, pos2):
return int(pos2[1])-int(pos1[1]) == 1 and abs(alphaToNum[pos2[0]]-alphaToNum[pos1[0]]) == 1
def canPieceCapture(piece, pos1, pos2):
if pos1 == pos2 or not(len(pos1) == len(pos2) == 2):
return False
if not isPosInsideBoard(pos1) or not isPosInsideBoard(pos2):
return False
if piece == 'P':
return pawnCapture(pos1, pos2)
if piece == 'p':
return pawnCapture(pos2, pos1)
return pieceFunctions[piece.lower()](pos1, pos2)
if __name__ == "__main__":
print(canPieceCapture('p', 'c5', 'd4'))
|
9f1db9e70e36af933abd037a2160a4962bed4b92 | hashjaco/PizzaHash | /PizzaEvent.py | 4,822 | 3.515625 | 4 | import numpy as np
class PizzaEvent:
def __init__(self, file):
self.max_slices, self.num_types, self.pizza_weights = getData(file)
''' Return a dictionary of pizza weights a'''
def returnPizzaDict(self):
pizza_dict = {}
for i in range(len(self.pizza_weights)):
pizza_dict.update({i: self.pizza_weights[i]})
return pizza_dict
''' This function traverses the matrix to determine the highest possible value we can achieve with the original options given
Time Complexity: Theta(n); Space Complexity: O(1) '''
def getMaxPossible(self, matrix):
index_value, curr_row, max_possible = matrix[self.num_types - 1][self.max_slices], self.num_types - 1, self.max_slices
while index_value != 1:
if curr_row and max_possible == 0:
return
elif max_possible == 0:
curr_column, curr_row = self.max_slices + 1, curr_row - 1
max_possible -= 1
index_value = matrix[curr_row][max_possible]
return max_possible, curr_row
''' This function navigates the matrix to build the solution array, determining the combination that will maximize our value '''
def getSubsetSolution(self, matrix, curr_column: int, curr_row: int):
solution = {}
while curr_column != 0:
if curr_row != 0 and matrix[curr_row-1][curr_column] == 1:
curr_row -= 1
continue
solution.update({curr_row: self.pizza_weights[curr_row]})
curr_column -= self.pizza_weights[curr_row]
return solution
''' This function runs the dynamic algorithm that fills the matrix with 1s and 0s conditionally '''
def fillMatrix(self, matrix):
for row in range(self.num_types):
for column in range(0, self.max_slices+1):
if column == 0:
matrix[row][column] = 0
continue
slices = self.pizza_weights[row]
if column == slices:
matrix[row][column] = 1
elif row == 0 and column != slices:
matrix[row][column] = 0
elif matrix[row-1][column] == 1:
matrix[row][column] = 1
else:
matrix[row][column] = matrix[row-1][column-slices]
return matrix
''' This is the bottom-up dynamic programming solution. Though extremely accurate, it's not so scalable. Time complexity: theta(N * w), Space complexity: theta(N * w) '''
def findCombination(self):
matrix = self.fillMatrix([[0 for x in range(int(self.max_slices) + 1)] for x in range(int(self.num_types))])
max_possible, curr_row = self.getMaxPossible(matrix)
return self.getSubsetSolution(matrix, max_possible, curr_row)
''' The Shimmy Search algorithm traverses the list of pizzas in descending order, summing the slices up along the way until it exceeds the maximum amount of slices, then it continues skips every value until it reaches one that puts it under the maximum and repeats the cycle '''
def shimmySearch(self):
size = len(self.pizza_weights)
assert size > 0
pizza_dict = self.returnPizzaDict()
solution_dict = {}
for i in range(size):
index = size - i - 1
next_value = pizza_dict[index]
p_keys, p_values = list(pizza_dict.keys()), list(pizza_dict.values())
curr_max = sum(list(solution_dict.values()))
curr_sum = curr_max + next_value
if curr_sum == self.max_slices:
solution_dict.update({index: next_value})
return solution_dict
elif curr_sum < self.max_slices:
low_delta = self.max_slices - curr_sum
solution_dict.update({index: next_value})
if low_delta not in pizza_dict.values():
continue
solution_dict.update({p_values.index(low_delta): low_delta})
return solution_dict
else:
high_delta = curr_sum - self.max_slices
if high_delta not in solution_dict.values():
continue
solution_dict.pop(p_keys[p_values.index(high_delta)]) and solution_dict.update({index: next_value})
# return solution_dict
return solution_dict
''' This function extracts the appropriate values from the given file '''
def getData(file):
file = open(f'data/{file}', 'r', encoding='utf-8')
max_slices, num_types = file.readline().replace("\n", "").split(" ")
pizza_weights = file.readline().replace("\n", "").split(" ")
file.close()
return int(max_slices), int(num_types), list(map(int, pizza_weights))
|
d8843676c975e46358544aad75cbd905519d0150 | juarezejp/python | /POO/ManipulacionCadenas.py | 1,185 | 4.15625 | 4 | nombre = "Eliadio JP"
nombre2 = "eladioJP"
numletra = "33k"
numeroS = "5555"
#devuelve en minusculas la cadena
print(nombre.lower())
#devuelve en mayusculas la cadena
print(nombre.upper())
#devuelve la cadena el primer caracter en mayuscula
print(nombre2.capitalize())
#devuelve true si la cadena es digitos
print (numletra.isdigit())
print (numeroS.isdigit())
#devuelve el indice minimo
print(nombre.find("da",0,6)) #-1 si no lo encuentra
print(nombre.find("i",0,6)) #indice del primer caracter
#devuelve el indice maximo en donde se encuentra la subcadena
print(nombre.rfind("i"))
print(nombre.rfind("i", 1, 4))
#devuelve verdadero si todos los caracteres son alfanumericos
print(nombre.isalnum())
print(numletra.isalnum())
print(numeroS.isalnum())
#devuelve true si todos los caracteres son alfabeticos o hay almenos un caracter
print(nombre.isalpha()) #regresa falso por que hay espacio en blanco
print(nombre2.isalpha())
print(numeroS.isalpha())
#devuelve lista de las palabras de la cadena
print(nombre.split())
#reemplaza una copia de la cadena en la que se sustitulle old por new
print(nombre.replace("i","A"))
print(nombre.replace("i","A",1)) #1 cantidad de veces a remplazar
|
d0592e75e11110e03897386dfce0c62413c4e816 | liaogx/python3-cookbook | /第四章:迭代器与生成器/4.10.py | 894 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'liao gao xiang'
# 你想在迭代一个序列的同时跟踪正在被处理的元素索引, 使用enumerate()函数
from collections import defaultdict
my_list = ['a', 'b', 'c']
for n, s in enumerate(my_list, start=1): # start表示开始的计数值
print(n, s)
# 这种情况在你遍历文件时想在错误消息中使用行号定位时候非常有用:
with open('file.txt', 'r', encoding='utf-8') as f:
for no, line in enumerate(f):
if 'error' in line:
print(f"{no}: {line}")
# 统计一篇文章里面每个单词出现的次数
with open('TOEFL.txt', 'r', encoding='utf-8') as f2:
word_summard = defaultdict(int)
for no, line in enumerate(f2):
words = (w.strip().lower() for w in line.split())
for word in words:
word_summard[word] += 1
print(word_summard)
|
139f51d8e67026cc3285627e1bc0ef2693437447 | sbasu7241/cryptopals | /Set2/Challenge9.py | 530 | 3.953125 | 4 | #!/usr/bin/env/python
def pkcs(data,block_size):
"""Returns data padded to the supplied block size in PKCS#7 format"""
pad_length = block_size - (len(data) % block_size)
# if pad_length is 0 it means data is of correct size but we will add extra blocks of padding
if pad_length == 0:
pad_length = block_size
#print(pad_length)
return data+ (chr(pad_length) * pad_length).encode() #.encode() will convert string to byte representation
print("[+] PKCS#7 padded byte_array >> "+str(pkcs(b'YELLOW SUBMARINE',20)))
|
50944898106de08dc5d00b72b84319195fd6cc41 | Clarxxon/kluster_analysis | /loadData.py | 551 | 3.53125 | 4 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def read_datafile(file_name):
data = pd.read_csv(file_name,delimiter=',', encoding="utf-8-sig")
return data
# data = read_datafile('winequality-red.csv')
data = read_datafile('cars.csv')
print(data['brand'])
# fig = plt.figure()
# ax1 = fig.add_subplot(111)
# ax1.set_title("Mains power stability")
# ax1.set_xlabel('time')
# ax1.set_ylabel('Mains voltage')
# ax1.plot(data['fixed acidity'],data['free sulfur dioxide'], 'bo')
# leg = ax1.legend()
# plt.show()
|
038278c1b3176df4ff30ddc5844c6c274d839cb8 | Delia86/2PEP21G01 | /c12/part2.py | 909 | 3.5625 | 4 | import tkinter
main_window = tkinter.Tk()
main_window.title("Text")
class TextWindow():
def __init__(self, root_window: tkinter.Tk):
self.root_window = root_window
self.text = tkinter.Text(self.root_window, height=25, width=80)
self.text.pack()
self.add_button = tkinter.Button(self.root_window, text='Add text', command=self.add_text)
self.add_button.pack()
self.select_button = tkinter.Button(self.root_window, text='Highlight text', command=self.set_background)
self.select_button.pack()
def add_text(self):
self.text.insert(tkinter.END, '\n text to insert')
def set_background(self):
self.text.tag_add('selection', tkinter.SEL_FIRST, tkinter.SEL_LAST)
self.text.tag_config('selection', background='yellow')
def run(self):
self.root_window.mainloop()
text = TextWindow(main_window)
text.run()
|
17835516a96add2241ed9669995a8e7c818aa19a | edaveballard/CS_class_activities | /Python/IteratedTournament/Tournament/player_tit4tat.py | 269 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 2 16:56:53 2019
@author: evan.ballard
"""
my_history = []
other_history = []
name = "Tit for Tat"
def next_move():
if len(other_history) == 0:
return 0
else:
return other_history[-1] |
689a996c808f2ebcecfddc1145038f6ddded9534 | Solbanc/Programacion_python | /Ejercicios python/Ejercicio practico 1.py | 1,576 | 4.0625 | 4 | print("Dias de Vacaciones Correspondientes a los trabajadores de Rappi.\n")
print("Clave 1 'Atencion a Clientes'")
print("Clave 2 'Logistica'")
print("Clave 3 'Gerencia'")
nom = input("Cual es el nombre del trabajador: ")
clave = int(input("Cual es la clavel del trabajador: " ))
tiempo = int(input("Cuanto tiempo ha trabajado: " ))
## Clave 1
if clave == 1 and tiempo == 1 :
print("El tiempo de vacaciones de", nom,"Es de 6 dias")
elif clave == 1 and tiempo == 2:
print("El tiempo de vaciones de" , nom , "Es de 14 dias")
elif clave == 1 and tiempo <= 6:
print("El tiempo de vaciones de" , nom , "Es de 14 dias")
elif clave == 1 and tiempo >= 7 :
print("El tiempo de vaciones de" , nom , "Es de 20 dias")
## Clave 2
if clave == 2 and tiempo == 1 :
print("El tiempo de vacaciones de", nom,"Es de 7 dias")
elif clave == 2 and tiempo == 2:
print("El tiempo de vaciones de" , nom , "Es de 15 dias")
elif clave == 2 and tiempo <= 6:
print("El tiempo de vaciones de" , nom , "Es de 15 dias")
elif clave == 2 and tiempo >= 7 :
print("El tiempo de vaciones de" , nom , "Es de 22 dias")
## Clave 3
if clave == 3 and tiempo == 1 :
print("El tiempo de vacaciones de", nom,"Es de 10 dias")
elif clave == 3 and tiempo == 2:
print("El tiempo de vaciones de" , nom , "Es de 20 dias")
elif clave == 3 and tiempo <= 6:
print("El tiempo de vaciones de" , nom , "Es de 20 dias")
elif clave == 3 and tiempo >= 7 :
print("El tiempo de vaciones de" , nom , "Es de 30 dias")
|
c5fc95f5a95b433bbb69945e8f83c03c400c9f4f | MarceloDL-A/Python | /13-Data_Visualization/Introduction_to_Matplotlib/Line_with_Shaded_Error.py | 1,840 | 4.0625 | 4 | import codecademylib
from matplotlib import pyplot as plt
hours_reported =[3, 2.5, 2.75, 2.5, 2.75, 3.0, 3.5, 3.25, 3.25, 3.5, 3.5, 3.75, 3.75,4, 4.0, 3.75, 4.0, 4.25, 4.25, 4.5, 4.5, 5.0, 5.25, 5, 5.25, 5.5, 5.5, 5.75, 5.25, 4.75]
exam_scores = [52.53, 59.05, 61.15, 61.72, 62.58, 62.98, 64.99, 67.63, 68.52, 70.29, 71.33, 72.15, 72.67, 73.85, 74.44, 75.62, 76.81, 77.82, 78.16, 78.94, 79.08, 80.31, 80.77, 81.37, 85.13, 85.38, 89.34, 90.75, 97.24, 98.31]
# Create your figure here
#Create a figure of width 10 and height 8.
plt.figure(figsize = (10, 8))
#Plot the exam_scores on the x-axis and the hours_reported on the y-axis, with a linewidth of 2
# Create your hours_lower_bound and hours_upper_bound lists here
#Lets assume the error on students reporting of their hours studying is 20%.
#Create a list hours_lower_bound, which has the elements of hours_reported minus 20%, and a list hours_upper_bound, which has the elements of hours_reported plus 20%.
#You can do this with a list comprehension that looks like:
#y_lower_bound = [element - (element * error_in_decimal) for element in original_list_of_y_values]
hours_lower_bound = [i*0.8 for i in hours_reported]
hours_upper_bound = [i*1.2 for i in hours_reported]
# Make your graph here
plt.plot(exam_scores, hours_reported,linewidth = 2)
#Shade the area between hours_lower_bound and hours_upper_bound with an alpha of 0.2.
plt.fill_between(exam_scores, hours_lower_bound,hours_upper_bound, alpha = 0.2)
#Give the plot the title 'Time spent studying vs final exam scores', x-axis label 'Score', and y-axis label 'Hours studying (self-reported)'.
plt.title("Time spent studying vs final exam scores")
plt.xlabel("Score")
plt.ylabel("Hours studying (self-reported)")
#Save your figure to a file called my_line_graph.png.
plt.savefig("my_line_graph.png")
plt.show() |
82b446d9f76af685659b432de5f84a2698efcb6e | zopepy/leetcode | /minimumindexsum.py | 884 | 3.84375 | 4 | class Solution:
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
list1dict = {}
l1 = len(list1)
l2 = len(list2)
for i in range(0, l1):
if list1[i] not in list1dict:
list1dict[list1[i]] = i
ans = float("inf")
min_ans = []
for i in range(0, l2):
if list2[i] in list1dict:
if ans == i+list1dict[list2[i]]:
min_ans.append(list2[i])
elif ans > i+list1dict[list2[i]]:
ans = min(ans, i+list1dict[list2[i]])
min_ans = [list2[i]]
return min_ans
left = ["Shogun","Tapioca Express","Burger King","KFC"]
right = ["KFC","Shogun","Burger King"]
s=Solution()
print(s.findRestaurant(left, right)) |
bb7556b100c87d3acb3efc291f3cf8465f36a9e7 | gil9red/SimplePyScripts | /split_text_by_fragments.py | 1,986 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
def split_text_by_fragments(text: str, fragment_length=50) -> list:
"""
Функция для разбития текста (<text>) на куски указанной длины (<fragment_length>).
"""
# Если длина фрагмента больше или равна длине текста, то сразу возвращаем список из одного элемента
if fragment_length >= len(text):
return [text]
fragments = list()
# Количество фрагментов
number = len(text) // fragment_length + 1
for i in range(number):
start = fragment_length * i
end = fragment_length * (i + 1)
fragments.append(text[start:end])
return fragments
if __name__ == "__main__":
text = """\
Брату в пору башмаки:
Не малы, не велики.
Их надели на Андрюшку,
Но ни с места он пока -
Он их принял за игрушку,
Глаз не сводит с башмака.
Мальчик с толком, с расстановкой
Занимается обновкой:
То погладит башмаки,
То потянет за шнурки.
Сел Андрей и поднял ногу,
Языком лизнул башмак...
Ну, теперь пора в дорогу,
Можно сделать первый шаг!
"""
fragments = split_text_by_fragments(text)
print(len(fragments), fragments)
assert "".join(fragments) == text
assert len(fragments) == 7
fragments = split_text_by_fragments(text, fragment_length=len(text))
print(len(fragments), fragments)
assert "".join(fragments) == text
assert len(fragments) == 1
fragments = split_text_by_fragments(text, fragment_length=9999)
print(len(fragments), fragments)
assert "".join(fragments) == text
assert len(fragments) == 1
|
4acf7c52945f382197827765badb714063590047 | Julien-Verdun/Project-Euler | /problems/problem56.py | 636 | 3.90625 | 4 | # Problem 56 : Powerful digit sum
def digital_sum(number):
"""
This function calculates the sum of digits of a given number.
"""
return sum([int(nb) for nb in list(str(number))])
def powerful_digit_sum():
"""
This function calculates the maximal sum of power number.
"""
max_sum = 1
max_i, max_j = 100, 100
for i in range(100):
for j in range(100):
max_ab = digital_sum((99-i)**(99-j))
if max_sum < max_ab:
max_sum = max_ab
max_i, max_j = i, j
return max_sum, 99-max_i, 99-max_j
print(powerful_digit_sum())
# Result 972
|
39e5441de5a47bb728a4b4314336188bdeb1d0f6 | alfredsusanto/CP1404 | /stockPrice.py | 752 | 3.90625 | 4 | import random
MAX_INCREASE = 0.175 # 10%
MAX_DECREASE = 0.05 # 5%
MIN_PRICE = 1
MAX_PRICE = 100
INITIAL_PRICE = 10.0
price = INITIAL_PRICE
def format_currency(price):
currency= "Starting price: $ {:.2f}".format(price)
return currency
result = format_currency(price)
print(result)
def format_currency2(price,day):
currency2= "On day {} price is: ${:,.2f}".format(day,price)
return currency2
day=0
while price >= MIN_PRICE and price <= MAX_PRICE:
priceChange = 0
day = day + 1
if random.randint(1, 2) == 1:
priceChange = random.uniform(0, MAX_INCREASE)
else:
priceChange = random.uniform(-MAX_DECREASE, 0)
price *= (1 + priceChange)
result2 = format_currency2(price,day)
print(result2)
|
168e7d485e22d14e0f0282f11ddd5ba0a753f41a | abbibrunton/python-stuff | /Python stuff/count_vowels.py | 282 | 3.984375 | 4 | word = input("please enter a word: ")
word_lower = word.lower()
vowels = "aeiou"
count = 0
for char in word.lower():
if char in vowels:
count += 1
else:
continue
if count == 1:
print("there is 1 vowel in", word)
else:
print("there are", count, "vowels in", word) |
f68e69983505091670add94376e866e748841e58 | redsarvesh/OOP-Python | /class/inheritance/fourth.py | 292 | 4.03125 | 4 | #!/usr/bin/python
class Person(object):
def __init__(self):
self.name = "{} {}".format("First","Last")
def f(self):
self.x=10
class Employee(Person):
def introduce(self):
print("Hi! My name is {}".format(self.name))
print self.x
e = Employee()
e.introduce()
|
e8e7dd9dd87cfff7e0e932e8d67d25499c146054 | jordanmiracle/learnpython3thehardway | /ex40.py | 588 | 4.1875 | 4 | class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print("I am classy apples!")
thing = MyStuff()
thing.apple()
print(thing.tangerine)
# Each time you creating a variable and assign it to MyStuff, you are creating a new object.
# You are instantiating, or creating an instance.
# This is dict style
# mystuff['apples']
# This is module style (after import)
# mystuff.apples()
# print(mystuff.tangerine)
# this is class style
# thing = MyStuff()
# thing.apples()
# print(thing.tangerine)
|
53be0f978919f374235742059850950a2467c9a5 | sandesvitor/code-lessons | /Cod3r (web + python + c#)/exercicios-python/e.py | 466 | 3.59375 | 4 | def dig_pow(n, p):
stack: list = []
sum: int = 0
limit: int = n
pot: int = p
while limit > 0:
digit: int = limit % 10
stack.append(digit)
limit //= 10
stack.reverse()
for num in stack:
sum += num ** pot
pot += 1
k: int = sum // n
if sum % n != 0:
return -1
else:
return k
numero = int(input("n: "))
potencia = int(input("p: "))
print(dig_pow(numero, potencia)) |
66622b4a63a78d1b940dd0104aaca7b5c78872a1 | fgaurat/python_07122020 | /tp1/tp2.py | 362 | 3.8125 | 4 | #!/usr/bin/env python
# words =[]
# w1 = input("mot 1: ")
# words.append(w1)
# w2 = input("mot 2: ")
# words.append(w2)
# w3 = input("mot 3: ")
# words.append(w3)
# print(50*"-")
# print(words)
# print(50*"-")
# for w in words:
# print(w.upper())
# print(50*"-")
# for i in range(len(words)):
# print(i,words[i])
# print(50*"-")
print( list(range(10)))
|
9b9001886189ea1246415cd260637e61e7e87115 | dsspasov/HackBulgaria | /week0/2-Python-harder-problems-set/problem28_test.py | 581 | 3.5625 | 4 | #problem28_test.py
import unittest
from problem28 import count_words
class TestWordCount(unittest.TestCase):
def test_empty_dict(self):
self.assertEqual({},count_words({}))
def test_not_empty_dict_with_different_elements(self):
result = count_words(["apple", "banana", "apple", "pie"])
self.assertEqual({'pie': 1, 'banana': 1, 'apple': 2},result)
def test_not_empty_dict_with_equal_element(self):
result = count_words(['a', 'a', 'a', 'a', 'a'])
self.assertEqual({'a' : 5}, result)
if __name__ == '__main__':
unittest.main()
|
480e6715772aa7670af4d7404bc5ac5802ddcb04 | piyush-bajaj7/substraction_BOT | /main.py | 2,445 | 3.5 | 4 | import time
import random
level_1_num1 = int(random.randint(100 , 120))
level_2_num1 = int(random.randint(121 , 140))
level_3_num1 = int(random.randint(141 , 160))
level_1_num2 = int(random.randint(30 , 50))
level_2_num2 = int(random.randint(51 , 60))
level_3_num2 = int(random.randint(61 , 90))
num1_randomizer = random.randint(1 , 3)
num2_randomizer = random.randint(1 , 3)
if num1_randomizer == 1 and num2_randomizer == 1: #1 to 1
you = int(input(f"{level_1_num1}-{level_1_num2}\n"))
elif num1_randomizer == 2 and num2_randomizer == 2: #2 to 2
you = int(input(f"{level_2_num1}-{level_2_num2}\n"))
elif num1_randomizer == 3 and num2_randomizer == 3: #3 to 3
you = int(input(f"{level_3_num1}-{level_3_num2}\n"))
elif num1_randomizer == 1 and num2_randomizer == 2: #1 to 2
you = int(input(f"{level_1_num1}-{level_2_num2}\n"))
elif num1_randomizer == 1 and num2_randomizer == 3: #1 to 3
you = int(input(f"{level_1_num1}-{level_3_num2}\n"))
elif num1_randomizer == 2 and num2_randomizer == 1: #2 to 1
you = int(input(f"{level_2_num2}-{level_1_num2}\n"))
elif num1_randomizer == 2 and num2_randomizer == 3: #2 to 3
you = int(input(f"{level_2_num1}-{level_3_num2}\n"))
elif num1_randomizer == 3 and num2_randomizer == 1: #3 to 1
you = int(input(f"{level_3_num1}-{level_1_num2}\n"))
elif num1_randomizer == 3 and num2_randomizer == 2: #3 to 2
you = int(input(f"{level_3_num1}-{level_2_num2}\n"))
if num1_randomizer == 1 and num2_randomizer == 1: #1 to 1
ans = level_1_num1-level_1_num2
elif num1_randomizer == 2 and num2_randomizer == 2: #2 to 2
ans = level_2_num1-level_2_num2
elif num1_randomizer == 3 and num2_randomizer == 3: #3 to 3
ans = level_3_num1-level_3_num2
elif num1_randomizer == 1 and num2_randomizer == 2: #1 to 2
ans = level_1_num1-level_2_num2
elif num1_randomizer == 1 and num2_randomizer == 3: #1 to 3
ans = level_1_num1-level_3_num2
elif num1_randomizer == 2 and num2_randomizer == 1: #2 to 1
ans = level_2_num2-level_1_num2
elif num1_randomizer == 2 and num2_randomizer == 3: #2 to 3
ans = level_2_num1-level_3_num2
elif num1_randomizer == 3 and num2_randomizer == 1: #3 to 1
ans = level_3_num1-level_1_num2
elif num1_randomizer == 3 and num2_randomizer == 2: #3 to 2
ans = level_3_num1-level_2_num2
if you == ans:
print("Yes its correct!!!")
else:
print(f"Its wrong \n The Correct answer is {ans}")
time.sleep(4)
print("MADE BY PiyushOP") |
8c72fbffdb03445ea74b7b75aea9366530942901 | Razdeep/PythonSnippets | /SEP06/02.py | 144 | 3.859375 | 4 | # color sorting using dictionaries
code={'red':'#ff000','blue':'#ffff','black':'#00000'}
for key in sorted(code):
print(key,':',code[key]) |
847ab87cd32c94b7faa9a2f3b8f625e07b61688c | mr-nishanth/PythonDT | /12-While in and For in.py | 416 | 3.90625 | 4 | # While in
Subject = ['Tamil', 'English', 'Maths', 'Science', 'Social Science']
Count = 0
while Count < len(Subject):
print(Subject[Count])
Count +=1
#print(len(Subject)) --->5
# For in
Games = ['Ludo', 'Freefire', 'Shooting', 'Car Racing']
for Game in Games:
print(Game)
Program = 'PYTHON'
for Char in Program:
print(Char) |
b2a77dd6b8fe303e7c79e4ba2a0ffff00480cfce | Verissimosem2/programacao-orientada-a-objetos | /listas/lista-de-exercicios-03/questão1.py | 222 | 4.09375 | 4 | numero = int (input("Por favor digite o primeiro numero: "))
numero_2 = int (input("Por favor digite o segundo numero: "))
if numero > numero_2:
print("Numero maior: ",numero)
else:
print("Numero maior: ",numero_2) |
3d4480d8f0d700bf88d6a752538d51b202f20521 | jundongq/emerald-shiner-detector | /utils_/removeGlare.py | 1,785 | 3.546875 | 4 | import cv2
import numpy as np
def removeGlare(img, satThreshold = 180, glareThreshold=240):
"""This function is used to remove light reflection on water surface during experiments,
it return a np.ndarray() in shape of (height, width, channel).
credit: http://www.amphident.de/en/blog/preprocessing-for-automatic-pattern-identification-in-wildlife-removing-glare.html
input: image
output: clean image"""
image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
h, s, v = cv2.split(hsv_image)
# return 1/0, 1 indicates satuation <180, 0 indicates satuation >180, which do not need to be inpainted.
# so nonSat serves as a mask, find all pixels that are not very saturated
# all non saturated pixels need to be set as 1 (non-zero), which will be inpainted
nonSat = s < satThreshold
# Slightly decrease the area of the non-satuared pixels by a erosion operation.
# return a kernel with designated shape, using erosion to minorly change the mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
nonSat = cv2.erode(nonSat.astype(np.uint8), kernel)
# Set all brightness values, where the pixels are still saturated to 0.
# Only non-zero pixels in the mask need to be inpainted. So the saturated pixels set as 0 (no need to inpaint)
v2 = v.copy()
# set all saturated pixels, which do not need to be inpainted as 0
v2[nonSat == 0] = 0
# glare as a mask filter out very bright pixels.
glare = v2 > glareThreshold
# Slightly increase the area for each pixel
glare = cv2.dilate(glare.astype(np.uint8), kernel)
glare = cv2.dilate(glare.astype(np.uint8), kernel)
clean_image = cv2.inpaint(image, glare, 3, cv2.INPAINT_TELEA)
clean_image = cv2.cvtColor(clean_image, cv2.COLOR_BGR2RGB)
return clean_image |
3276b6e64537e3b3fb2bef850b968a727ac58f11 | xw0220/pythoncourse | /experiment6/test8.py | 458 | 3.5 | 4 | def qiuhe(x):
feizhengshuliebiao=[]
if x==[]:
return "输入不能为空列表"
else:
for item in x:
if type(item)!=int:
feizhengshuliebiao.append((item,type(item)))
if feizhengshuliebiao==[]:
return sum(x)
else:
print("元素类型错误,要求所有元素都为整数")
return feizhengshuliebiao
m=[1,2,3,4,5]
n=[1,'bai','hu',3,4]
print(qiuhe(n)) |
827a97706612c4b08787293e38e44ad73fceaae9 | sakurasakura1996/Leetcode | /alibaba_online_codeing/每周限时赛第一场(内测版)/商品列表.py | 1,823 | 4.03125 | 4 | """
描述
有一个商品列表,该列表是由L1、L2两个子列表拼接而成。当用户浏览并翻页时,需要从列表L1、L2中获取商品进行展示。
展示规则如下:
1. 用户可以进行多次翻页,用offset表示用户已经浏览过的商品数量。比如,offset是4,表示用户已经看了4个商品。
2. n表示一个页面可以展示的商品数量。
3. 展示商品时首先使用列表L1,如果列表L1不够,再从列表L2中选取商品。
4. 从列表L2中补全商品时,也可能存在数量不足的情况。
给定offset,n,列表L1和L2的长度。
请根据上述规则,计算列表L1和L2中哪些商品在当前页面被展示了。
你需要根据notice里的规则输出两个区间。区间段使用半闭半开区间表示,即包含起点,不包含终点。
比如,区间[0,1)表示第一个商品。如果某个列表的区间为空,使用[0, 0)表示,如果某个列表被跳过,使用[len, len)表示,len表示列表的长度。
示例
样例 1:
输入:
2
4
4
4
输出:
[2,4,0,2]
样例 2:
输入:
1
2
4
4
输出:
[1,3,0,0]
"""
# 理清思路比较重要,主要在于如何判断
class Solution:
def ProductList(self, offset, n, len1, len2):
if offset + n <= len1:
# 全部都是L1中的商品
return [offset,offset+n,0,0]
elif offset <= len1:
if n - len1 + offset > len2:
return [offset, len1,0, len2]
return [offset, len1,0,n-len1+offset]
elif offset <= len1 + len2:
if offset - len1 + n > len2:
return [len1,len1,offset-len1,len2]
return [len1,len1,offset-len1,offset-len1+n]
else:
return [len1,len1,len2,len2]
solu = Solution()
ans = solu.ProductList(1,2,4,4)
print(ans)
|
4e5dd83a5bf18543528d65aa75e729c5dd8b675e | FelipePRodrigues/hackerrank-practice | /interview-preparation-kit/string-manipulation/alternating-characters/alternating_characters_test.py | 325 | 3.515625 | 4 | from alternating_characters_solution import alternatingCharacters
class TestAlternatingCharacters:
def test_one(self):
assert alternatingCharacters("AAAA") == 3
def test_two(self):
assert alternatingCharacters("ABAB") == 0
def test_three(self):
assert alternatingCharacters("AABB") == 2 |
bb4b2fa278b9aca268e94de0ad3343d8b188d3f4 | JaredRentz/gittest | /statements.py | 661 | 3.78125 | 4 | # if, elif, else Statements
'''
if case1:
perform action 1
elif case2:
perform action 2
else:
perform action 3
'''
x = [2,3,4,5,7,8]
y = 6
z = 3
'''
if x>y:
print(x)
elif y>z:
print(y)
else:
print(z)
'''
# FOR LOOPS IN PYTHON
#for item in x:
#print(item)
badge_numbers = [1,3,432,43242,432]
'''
for x in badge_numbers:
if x % 3 == 0:
print(x)
'''
list_sum = 0
'''
for num in badge_numbers:
list_sum += num
print(list_sum)
'''
# Iterating through a Dictionary
d = {"k1":1, "k2":2, "k3":3}
#for k,v in d.items():
# print(v)
'''
While Loops
'''
x = 0
while x <= 10:
print("x is equal to: ",x)
x += 1
if x == 4:
break
else:
print("Done!")
|
4b67852d9119cc1d51a64abb5ae62a88c11ef325 | yashitha985/python | /hunter1.py | 183 | 3.5 | 4 | a=int(input())
b=list(map(int,input().split()))
c=[]
for i in b:
if(b.count(i)>=2 and i not in c):
c.append(i)
if(len(c)==0):
print("unique")
else:
for i in c:
print(i,end="")
|
9f6b77e4cf889ff94d96548a2fd7162c072c0e4d | danstelian/python_misc | /oop/oop_03_inheritance.py | 2,753 | 3.90625 | 4 | """
Add two subclasses to the curent Employee class
"""
class Employee:
num_of_emp = 0
def __init__(self, first, last, salary):
self.first = first
self.last = last
self.salary = salary
Employee.num_of_emp += 1
def __str__(self):
return f'{self.first} {self.last} [{self.email}]'
def __repr__(self):
cls_name = self.__class__.__name__
return f"{cls_name}('{self.first}', '{self.last}', {self.salary})"
@property # 1
def salary(self):
return self.__salary
@salary.setter # 2
def salary(self, value):
assert isinstance(value, int), 'salary must be integer'
assert value != 0, 'salary must not be 0'
self.__salary = value
# chance 1 & 2 with some kind of descriptor (learn descriptors)
@property
def email(self):
return f'{self.first}.{self.last}@company.com'
@property
def fullname(self):
return f'{self.first} {self.last}'
@fullname.setter
def fullname(self, name):
self.first, self.last = name.split()
class Developer(Employee):
def __init__(self, first, last, salary, prog_lang):
super().__init__(first, last, salary)
self.prog_lang = prog_lang
def __repr__(self):
cls_name = self.__class__.__name__
return f"{cls_name}('{self.first}', '{self.last}', {self.salary}, '{self.prog_lang}')"
class Manager(Employee):
def __init__(self, first, last, salary, employees=None):
super().__init__(first, last, salary)
if employees is None:
self.employees = []
else:
# should assert if every employee in the list is instance of class Employee...
assert isinstance(employees, list), 'employees must be a list'
self.employees = employees[:]
def add_emp(self, new_emp):
if new_emp not in self.employees:
self.employees.append(new_emp)
def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
def print_emp(self):
if not self.employees:
print('empty list')
else:
print('-->', end='')
for emp in self.employees:
print(f'\t{emp.fullname}')
emp_1 = Employee('John', 'Smith', 1000)
print(emp_1)
# dev_1 = Developer('Tom', 'Green', 0, 'Python') # still getting error messages
dev_1 = Developer('Tom', 'Green', 1200, 'Python')
print(repr(dev_1)) # rewrote the __repr__ sepecial method to accommodate the 'prog_lang' attribute
mng_1 = Manager('Jim', 'Thomas', 1600, [emp_1])
# mng_1 = Manager('Jim', 'Thomas', 1600, [])
# mng_1 = Manager('Jim', 'Thomas', 1600)
print(mng_1)
# mng_1.add_emp(emp_1)
mng_1.add_emp(dev_1)
mng_1.print_emp()
|
cef96eb045f0cf281483a18e4dda1d080f078932 | BeckerFelix/KITTI-to-tfrecords | /progress.py | 1,249 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# Print iterations progress to the terminal
import sys
def print_progress_bar(iteration, total, bar_length=50):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
"""
str_format = "{0:." + str(1) + "f}"
percents = str_format.format(100 * (iteration / float(total)))
filled_length = int(round(bar_length * iteration / float(total)))
progress_bar= '█' * filled_length + '-' * (bar_length - filled_length)
sys.stdout.write('\r |%s| %s%s' % (progress_bar, percents, '%')),
# Print New Line on Complete
if iteration == total:
print()
#################
# Sample Usage
################
#import progress
#from progress import printProgressBar
#for i in range (456):
# print_progress_bar(i,456)
# performe some calculation...
################
# Sample Output
################
# |█████████████████████████████████████████████-----| 90.0%
|
1a5860658e36b1ba322392f11f5057233fa97259 | byzhang/conclave | /conclave/rel.py | 3,143 | 3.84375 | 4 | """
Data structures to represent relations (i.e., data sets).
"""
import conclave.utils as utils
class Column:
"""
Column data structure.
"""
def __init__(self, rel_name: str, name: str, idx: int, type_str: str, trust_set: set):
"""
Initialize object.
:param rel_name: name of corresponding relation
:param name: name of column
:param idx: integer index of the column in the relation
:param type_str: describes type of values in column (currently only "INTEGER" supported)
:param trust_set: parties trusted to learn this column in the clear
"""
if type_str not in {"INTEGER"}:
raise Exception("Type not supported {}".format(type_str))
self.rel_name = rel_name
self.name = name
self.idx = idx
self.type_str = type_str
self.trust_set = trust_set
def get_name(self):
"""Return column name."""
return self.name
def get_idx(self):
"""Return column index."""
return self.idx
def dbg_str(self):
"""Return column name and trust set as string."""
coll_set_str = " ".join(sorted([str(party) for party in self.trust_set]))
return self.get_name() + " " + "{" + coll_set_str + "}"
def merge_coll_sets_in(self, other_coll_sets: set):
"""Merge collusion sets into column."""
self.trust_set = utils.merge_coll_sets(self.trust_set, other_coll_sets)
def __str__(self):
"""Return string representation of column object."""
return self.get_name()
class Relation:
"""
Relation data structure.
"""
def __init__(self, name: str, columns: list, stored_with: set):
"""Initialize object."""
self.name = name
self.columns = columns
self.stored_with = stored_with # Ownership of this data set. Does this refer to secret shares or open data?
def rename(self, new_name):
"""Rename relation."""
self.name = new_name
for col in self.columns:
col.rel_name = new_name
def is_shared(self):
"""Determine if this relation is shared."""
return len(self.stored_with) > 1
def update_column_indexes(self):
"""
Makes sure column indexes are same as the columns' positions
in the list. Call this after inserting new columns or otherwise
changing their order.
"""
for idx, col in enumerate(self.columns):
col.idx = idx
def update_columns(self):
"""Update relation name in relation column objects."""
self.update_column_indexes()
for col in self.columns:
col.rel_name = self.name
def dbg_str(self):
"""Return extended string representation for debugging."""
col_str = ", ".join([col.dbg_str() for col in self.columns])
return "{}([{}]) {}".format(self.name, col_str, self.stored_with)
def __str__(self):
"""Return string representation of relation."""
col_str = ", ".join([str(col) for col in self.columns])
return "{}([{}])".format(self.name, col_str)
|
890456ed386df13bdf79c4b212b5b3d488be46c4 | xelab04/0H-H1-Bot | /0h h1 bot.py | 5,050 | 3.6875 | 4 | array = []
file_dest = "input.txt"
with open(file_dest,"r") as file:
lines = file.readlines()
for line in lines:
array.append((line.strip("\n")).split(","))
for row in array:
print(row)
print("")
grid_size = len(array)
def output(array):
for row in array:
print(row)
def is_colour(x,y,dx1,dx2,dy1,dy2,grid):
try:
if grid[y][x] == "0":
sq_one = grid[y+dy1][x+dx1]
sq_two = grid[y+dy2][x+dx2]
if (sq_one == sq_two) and sq_one != "0":
return True,sq_one
else: return False,None
else: return False,None
except IndexError: return False,None
def not_really(colour):
if colour == "R":
return "B"
elif colour == "B":
return "R"
else:
print(f"Invalid Colour {colour} Passed Into Function")
def compare(line_one,line_two):
length = len(line_one)
stupid_list = []
for i in range(length):
if line_one[i] != line_two[i] and line_one[i] != "0":
return False,None
else:
if line_one[i] == "0":
stupid_list.append((i,line_two[i]))
return True,stupid_list
def thing(direction):
var = False
colour = None
if direction == "x":
a,b,c,d = 1,-1,1,2
e,f,g,h = 0,0,0,0
else:
a,b,c,d = 0,0,0,0
e,f,g,h = 1,-1,1,2
if var == False:
try: var,colour = is_colour(x,y,a,b,e,f,array)
except: pass
if var == False:
try: var,colour = is_colour(x,y,c,d,g,h,array)
except: pass
if var == False:
try: var,colour = is_colour(x,y,-c,-d,-g,-h,array)
except: pass
return var,colour
change = True
while change == True:
change = False
#ROWS
for y in range(grid_size):
line = array[y]
for x in range(grid_size):
#START FIRST RULE
var,colour = thing("x")
if var == True:
change = True
array[y][x] = (not_really(colour))
#END FIRST RULE
#START SECOND RULE
if line.count("0") > 0 and array[y][x] == "0":# and change == False:
r_count = line.count("R")
b_count = line.count("B")
if r_count == grid_size/2:
array[y][x] = (not_really("R"))
change = True
if b_count == grid_size/2:
array[y][x] = (not_really("B"))
change = True
#END SECOND RULE
#START THIRD RULE
if line.count("0") == 2:# and change == False:
for line_2 in array:
if line_2.count("0") == 0:
same_list, stupid_list = compare(line,line_2)
if same_list == True:
array[y][stupid_list[0][0]] = not_really(stupid_list[0][1])#inversing colour
#END THIRD RULE
#END ROWS
#COLUMNS
for x in range(grid_size):
temp_list = []
for y in range(grid_size):
temp_list.append(array[y][x])
for y in range(grid_size):
var,colour = thing("y")
if var == True:
change = True
array[y][x] = (not_really(colour))
if temp_list.count("0") > 0 and array[y][x] == "0" and change == False:
r_count = temp_list.count("R")
b_count = temp_list.count("B")
if r_count == grid_size/2:
array[y][x] = (not_really("R"))
change = True
if b_count == grid_size/2:
array[y][x] = (not_really("B"))
change = True
if temp_list.count("0") == 2 and change == False:
for nx in range(grid_size):
new_temp_list = []
for ny in range(grid_size):
new_temp_list.append(array[ny][nx])
if new_temp_list.count("0") == 0:
same_list, stupid_list = compare(temp_list,new_temp_list)
if same_list == True:
array[stupid_list[0][0]][x] = not_really(stupid_list[0][1])#inversing colour
#changing array values
output(array)
with open("output.txt","w") as file:
for line in array:
text = ""
for i in range(grid_size):
if i > 0:
text = text + "," + line[i]
else:
text = line[i]
file.writelines(text + "\n")
|
f06b865266ddf2e30345ff92847e23eef83ae733 | lxchavez/Yeezy-Taught-Me | /src/MSongsDB/Tasks_Demos/SQLite/list_all_tracks_from_db.py | 2,909 | 3.75 | 4 | """
Thierry Bertin-Mahieux (2010) Columbia University
tb2332@columbia.edu
This code creates a text file with all track ID, song ID, artist name and
song name. Does it from the track_metadata.db
format is:
trackID<SEP>songID<SEP>artist name<SEP>song title
This is part of the Million Song Dataset project from
LabROSA (Columbia University) and The Echo Nest.
Copyright 2010, Thierry Bertin-Mahieux
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
import glob
import string
import time
import datetime
import numpy as np
try:
import sqlite3
except ImportError:
print 'you need sqlite3 installed to use this program'
sys.exit(0)
def die_with_usage():
""" HELP MENU """
print 'list_all_tracks_from_db.py'
print ' by T. Bertin-Mahieux (2010) Columbia University'
print 'Code to create a list of all tracks in the dataset as'
print 'a text file. Assumes track_metadata.db already exists.'
print "Format is (IDs are EchoNest's):"
print 'trackID<SEP>songID<SEP>artist name<SEP>song title'
print ' '
print 'usage:'
print ' python list_all_tracks_from_db.py <track_metadata.db> <output.txt>'
print ''
sys.exit(0)
if __name__ == '__main__':
# help menu
if len(sys.argv) < 3:
die_with_usage()
# params
dbfile = sys.argv[1]
output = sys.argv[2]
# sanity check
if not os.path.isfile(dbfile):
print 'ERROR: can not find database:',dbfile
sys.exit(0)
if os.path.exists(output):
print 'ERROR: file',output,'exists, delete or provide a new name'
sys.exit(0)
# start time
t1 = time.time()
# connect to the db
conn = sqlite3.connect(dbfile)
# get what we want
q = 'SELECT track_id,song_id,artist_name,title FROM songs'
res = conn.execute(q)
alldata = res.fetchall() # takes time and memory!
# close connection to db
conn.close()
# sanity check
if len(alldata) != 1000000:
print 'NOT A MILLION TRACKS FOUND!'
# write to file
f = open(output,'w')
for data in alldata:
f.write(data[0]+'<SEP>'+data[1]+'<SEP>')
f.write( data[2].encode('utf-8') +'<SEP>')
f.write( data[3].encode('utf-8') + '\n' )
f.close()
# done
t2 = time.time()
stimelength = str(datetime.timedelta(seconds=t2-t1))
print 'file',output,'created in',stimelength
|
06f1818880cc91aaea5f74ec35f532bf4b0c84bc | xwang322/Coding-Interview | /uber/uber_algo/MergeNumsToRanges_UB.py | 3,160 | 3.625 | 4 | /*
* 给定一个整数数列比如-2,-1,2,3,返回代表数列的range比如-2--1,2-3
* 给出正确做法(排序+遍历),写了几个testcase
* 然后来了个followup,给出range,返回任何一个对应整数数列,遍历硬做就可以了,需要考虑一下横杠的不同情况
**/
def MergeIntToRanges(nums):
if not nums:
return []
if len(nums) == 1:
return [str(nums[0])+'-'+str(nums[0])]
nums.sort()
answer = []
temp = 0
i = 0
while i < len(nums):
while i < len(nums)-1 and (nums[i]+1 == nums[i+1] or nums[i] == nums[i+1]):
i += 1
if i == temp:
answer.append(str(nums[i])+'-'+str(nums[i]))
temp += 1
else:
answer.append(str(nums[temp])+'-'+str(nums[i]))
temp = i+1
i += 1
return answer
answer = MergeIntToRanges([-2, -2, -1, -1, 0, 1, 2, 3, 5, 7])
print answer
def RangesToIntSeparate(strings):
if not strings:
return []
answer = []
for string in strings:
length = len(string)
for i in range(1, length-1):
if (string[i-1].isdigit() and string[i+1].isdigit() and string[i] == '-') or (string[i] == '-' and string[i+1] == '-'):
num1 = int(string[:i])
num2 = int(string[i+1:])
answer += [i for i in range(num1, num2+1)]
break
if '-' not in string:
answer.append(int(string))
if '-' == string[0] and string.count('-') == 1:
answer.append(int(string))
answer.sort()
return answer
answer = RangesToIntSeparate(['-7','-2--1', '3-5', '-9', '12'])
print answer
# If you merge them together, you remove the duplicates
def MergeIntToRanges(nums):
if not nums:
return []
if len(nums) == 1:
return [str(nums[0])+'-'+str(nums[0])]
nums.sort()
answer = []
temp = 0
i = 0
while i < len(nums):
while i < len(nums)-1 and (nums[i]+1 == nums[i+1] or nums[i] == nums[i+1]):
i += 1
if i == temp:
answer.append(str(nums[i])+'-'+str(nums[i]))
temp += 1
else:
answer.append(str(nums[temp])+'-'+str(nums[i]))
temp = i+1
i += 1
return answer
def RangesToIntSeparate(strings):
if not strings:
return []
answer = []
for string in strings:
length = len(string)
for i in range(1, length-1):
if (string[i-1].isdigit() and string[i+1].isdigit() and string[i] == '-') or (string[i] == '-' and string[i+1] == '-'):
num1 = int(string[:i])
num2 = int(string[i+1:])
answer += [i for i in range(num1, num2+1)]
break
if '-' not in string:
answer.append(int(string))
if '-' == string[0] and string.count('-') == 1:
answer.append(int(string))
answer.sort()
return answer
answer = RangesToIntSeparate(MergeIntToRanges([-2, -2, -1, -1, 0, 1, 2, 3, 5, 7]))
print answer
|
c356d4ab84c641de5124a874f506405166af84d0 | Zikx/Algorithm | /Baekjoon/Sort/2750.py | 106 | 3.5 | 4 | n = int(input())
l = [ int(input()) for i in range(n)]
l.sort()
for e in l:
print(e,end="\n") |
6414625d38f35da285cf981150d2f0f60821c948 | Munyiwamwangi/politico | /app/tests/test_petition_model.py | 1,072 | 3.59375 | 4 | # petition class tests
import unittest
from app.api.model.petition import Petition
class PetitionModelTestCases(unittest.TestCase):
""" Test class for petition model """
def setUp(self):
"""Create a petition object instance
:arg: office, created_by, body, evidence
:return: petition instance
"""
self.new_petition = Petition(
office=1,
contested_by=2,
created_by=2,
body='Some reason for the petition',
evidence='http://get.go.com'
)
def test_petition_object_creation(self):
""" test petition object is instantiated properly """
self.assertEqual(self.new_petition.office, 1)
self.assertEqual(self.new_petition.contested_by, 2)
self.assertEqual(self.new_petition.contested_by, 2)
self.assertEqual(self.new_petition.body,
'Some reason for the petition')
self.assertEqual(self.new_petition.evidence, 'http://get.go.com')
self.assertTrue(self.new_petition.created_on)
|
7809c18f46df54285ba693eac37cc7a86225b417 | PierfrancescoArdino/LUS-MidTerm-Project | /compute_output.py | 942 | 3.59375 | 4 | #! /bin/python3
'''
LUS mid-term project, Spring 2017
Student: Pierfrancesco Ardino, 189159
This script simply check if the output concept is in the concept list, if not it means that the output concept is the word
itself and so has to be changed into the O concept
#### HOW-TO USE####
Do not run this script independently.
Please refer to the elaborator_w2c_without_O.sh that will creates the lexicon, runs this script and trains the automaton
Do not touch any file in the directory.
'''
import sys
output_original = sys.argv[1]
output_file = sys.argv[2]
concept_file = sys.argv[3]
with open(output_original) as f, open(concept_file) as f1, open(output_file, "w") as w:
tmp = f.read().split('\n')
tmp1 = f1.read().split('\n')
print(tmp)
for line in tmp:
if line != '':
if line in tmp1:
print(line,file=w)
else:
print("O", file=w)
else:
print("", file=w) |
dc90049ee28dea522ab3a5aa9a69dfaf65d1ad43 | lmhbali16/algorithms | /CTCI/chapter_1/string_compression.py | 1,428 | 4.3125 | 4 | '''
Implement a method to perform basic string compression using the counts of repeated characters.
For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not
become smaller than the original string, your method should return
the original string. You can assume the string has only uppercase and lowercase letters (a - z).
'''
def pick_shortest(word_number: str, word_original: str) -> str:
if len(word_original) < len(word_number):
return word_original
else:
return word_number
# Okay, this is not the task but harder
def string_compression(word: str) -> str:
result = ""
current_letter = word[0]
count = 0
i = 0
j = 0
while i < len(word):
if word[i] == current_letter:
count += 1
else:
new_string = current_letter + str(count)
new_string = pick_shortest(new_string, word[j:i])
result += new_string
count = 1
current_letter = word[i]
j = i
i += 1
return result
def string_compression_original(word: str) -> str:
result = ""
current_letter = word[0]
count = 0
i = 0
j = 0
while i < len(word):
if word[i] == current_letter:
count += 1
else:
new_string = current_letter + str(count)
result += new_string
count = 1
current_letter = word[i]
j = i
i += 1
if len(result) < len(word):
return result
return word
print(string_compression('aaaabbbffFFFLLDDDWW'))
print(string_compression_original('abdfDFE')) |
196f6a6bb2c1c4e47139e1da7d4d3e5cd234a477 | IagoFrancisco22/listaDeExerciciosPython | /Primeira lista de exercicios Python/exercicio5.py | 392 | 3.921875 | 4 | #enunciado
print('''Solicite o preço de uma mercadoria e o percentual de desconto. Exiba o valor do desconto e o
preço a pagar.''')
m = float(input("Digite o preco da mercadoria:"))#solicitar preço mercadoria(m)
d= int(input("Digite a porcentagem de desconto:"))#percentual de desconto (d)
p=d/100#porcentagem(p)
print("Valor do desconto=",p*m)
print("Preco a pagar=",m-p*m)
|
769b7f34a39cc01986f64c141587f762b938bae2 | gabrielalvesfortunato/Formacao-Python-alura-OO | /conta.py | 2,280 | 3.828125 | 4 | # Para se nomear objetos usa-se o padrão Camel Case.
class ContaCorrente:
# Definindo o Construtor da classe
def __init__(self, numero, titular, limite = 1000, saldo = 0):
print("Construindo objeto {}".format(self))
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
@property
def limite(self):
return self.__limite
@limite.setter
def limite(self, novo_limite):
self.__limite = novo_limite
@property
def saldo(self):
return self.__saldo
@property
def titular(self):
return self.__titular.title()
def extrato(self):
print("\nConta: {} \nTitular: {} \nSaldo: R${} \nLimite: R${}\n".format(self.__numero, self.__titular,
self.__saldo, self.__limite))
def depositar(self, valor):
if self.__limite < 1000:
deposito_limite = abs(valor - self.__limite)
self.__saldo = self.__saldo + deposito_limite
self.__limite = 1000.00
print("\nDepósito no valor de {} realizado com sucesso!".format(valor))
elif self.__limite == 1000:
self.__saldo += valor
print("\nDepósito no valor de {} realizado com sucesso!".format(valor))
def __pode_sacar(self, valor_a_sacar):
valor_disponivel_para_saque = self.__saldo + self.__limite
return valor_disponivel_para_saque >= valor_a_sacar
def sacar(self, valor):
if self.__pode_sacar():
if self.__saldo >= valor:
self.__saldo -= valor
print("\nSaque no valor de {} realizado com sucesso!".format(valor))
else:
retira_limite = abs(self.__saldo - valor)
self.__limite -= retira_limite
self.__saldo = 0.0
print("\nSaque no valor de {} realizado com sucesso!".format(valor))
else:
print("\nO valor que deseja sacar e maior que o valor disponível em conta.")
def transferir(self, valor, conta_destino):
self.sacar(valor)
conta_destino.depositar(valor) |
d6e90fa15a33a37e2b610436c1ff1c920733150b | proformatique/algo | /mpsi4_23_10.py | 1,670 | 4.09375 | 4 | def somme2(A, B) -> list:
'''Calcule la somme terme à terme de A et B.
Parameters:
-----------
A : list
Premier vecteur
B : list
2eme vecteur
Returns
-------
C : list
la somme de A + B | ci = ai + bi
Examples
--------
>>> A = [1, 2, 3]
>>> B = [3, 2, 1]
>>> somme2(A, B)
[4, 4, 4]
'''
assert len(A) == len(B), 'Données non valides!'
# Méthode 1 : Parcourir les trois listes
n = len(A)
C = [None] * n
for i in range(n):
C[i] = A[i] + B[i]
return C
def somme2_2(A, B):
# Méthode 2 : MI
C = [] # R. I
for a, b in zip(A, B):
C += [a + b] # Construction
return C # R.F
def somme2_3(A, B):
# Méthode 3 : while
n = len(A)
i = 0
C = [None] * n
while i < n:
C[i] = A[i] + B[i]
i += 1
return C
def inverser(liste) -> list:
'''Retourne une copie inversée d'une liste.
Parameters:
-----------
liste : list
liste de valeurs
Returns
-------
copie : list
copie inversée de liste
Examples
--------
>>> inverser([1, 2, 3])
[3, 2, 1]
'''
N = len(liste) - 1
copie = []
for i in range(N, -1, -1):
copie += [liste[i]]
return copie
def inverser2(liste):
# Méthode 2
N = len(liste)
copie = []
for i in range(N):
copie += [liste[- i - 1]] # [liste[~i]]
return copie
if __name__ == '__main__':
import doctest as dt
dt.testmod()
|
e2a8b6dc028f4f0604f2da8a9590cd8a7cfea4f9 | Malvado86/Crash_Course_on_python | /Code_Style_rectangle.py | 203 | 3.84375 | 4 | '''
Created on 21 de mar de 2020
@author: tsjabrantes
'''
def rectangle_area(base, height):
z = (base * height) # the area is base*height
print("The area is " + str(z))
rectangle_area(5,6) |
66633dd3813544e164ff62f2e448e6655b213417 | xiaojieluo/savemylink | /lib/util_bak.py | 1,068 | 3.515625 | 4 | #!/usr/bin/env python
# coding=utf-8
import datetime
import time
def convert(data):
"""
dict bytes key to str value
"""
if not isinstance(data, dict):
return data
return dict([(bytes.decode(k), bytes.decode(v)) for k, v in data.items()])
def ago(times, accurate=False):
now = int(time.time())
times = int(times)
c = now - times
#print(c)
if c < 60:
msg = "{second} Second ago".format(second=c)
elif c >= 60 and c < 3600:
msg = "{minute} minute ago".format(minute=int(c/60))
elif c >= 3600 and c < 86400:
msg = "{hour} hours ago".format(hour=int(c/3600))
elif c >= 86400 and c < 604800:
msg = "{day} days ago".format(day=int(c/86400))
elif c >= 604800 and c < 2592000:
msg = "{week} weeks ago".format(week=int(c/604800))
elif c >= 2592000 and c < 31114000:
msg = "{month} months ago".format(month=int(c/2592000))
elif c >= 31114000:
msg = "{year} years ago".format(year=int(c/31114000))
return msg
print(msg)
ago(1483849573)
|
6a742645d1d438ac2ecc3ee032777451b12be06a | jatinkatyal13/PythonForDataScience | /codes/check_cons_ones.py | 204 | 3.625 | 4 | n=input('enter the binary number: ')
k=input('enter the value of K: ')
g=0
l=int(k)
g='1'*l
if(g in n):
print("yes there are given no. of consecutive 1's in the binary number")
else:
print('NO') |
4330424b22dcab4225654323d7096aae7c2de33e | YoyinZyc/Leetcode_Python | /Sort/Pro147_Insertion_Sort_List.py | 1,122 | 3.84375 | 4 | '''
Sort_Medium
9.19 6:31pm
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
end = head
while end.next:
if end.next.val < head.val:
node = end.next
end.next = end.next.next
node.next = head
head = node
elif end.next.val >= end.val:
end = end.next
else:
indexNode = head
while indexNode.next:
if end.next.val >= indexNode.val and end.next.val < indexNode.next.val:
node = end.next
end.next = end.next.next
node.next = indexNode.next
indexNode.next = node
break
indexNode = indexNode.next
return head
|
813dd1da95a95bb4170d71e883c047694ca2ace3 | ollyhayes/advent-of-code | /src/2019/day03.py | 1,731 | 3.5 | 4 | import os
from typing import List, Tuple, Dict, Set
def parse_input(input_raw: str) -> List[List[Tuple[str, int]]]:
return [
[(command[0], int(command[1:])) for command in path.split(",")]
for path
in input_raw.split("\n")
]
directions: Dict[str, Tuple[int, int]] = {
"R": (1,0),
"L": (-1,0),
"U": (0,1),
"D": (0,-1),
}
def plot2(input: List[Tuple[str, int]]) -> Dict[Tuple[int, int], int]:
occupied_positions: Dict[Tuple[int, int], int] = {}
position: Tuple[int, int] = (0, 0)
distance_travelled = 0
for direction, length in input:
direction_parts = directions[direction]
for _ in range(0, length):
position = position[0] + direction_parts[0], position[1] + direction_parts[1]
occupied_positions[position] = distance_travelled
distance_travelled += 1
return occupied_positions
def compute_part_1(input: str) -> int:
inputs = parse_input(input)
path1 = plot2(inputs[0])
path2 = plot2(inputs[1])
intersections = path1.keys() & path2.keys()
distances = [abs(position[0]) + abs(position[1]) for position in intersections]
return min(distances)
def compute_part_2(input: str) -> int:
inputs = parse_input(input)
path1 = plot2(inputs[0])
path2 = plot2(inputs[1])
intersection_points = path1.keys() & path2.keys()
distances = [
path1[intersection_point] + path2[intersection_point]
for intersection_point
in intersection_points
]
return min(distances) + 2
def main() -> int:
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, "day03_input.txt")
with open(filename, "r") as input_file:
input = input_file.read()
print(f"part1: {compute_part_1(input)}")
print(f"part2: {compute_part_2(input)}")
return 0
if __name__ == '__main__':
exit(main()) |
c6ac1cacde7cc5f5da7faf35f7fbc66e8cdc8805 | arsalan2400/HPM573S18_AHMED_HW1 | /HW1Problem4.py | 840 | 4.28125 | 4 | #Print ours1 and ours2. Describe how ours1and ours2differfrom each other.#
yours = ['Yale','MIT','Berkeley']
mine= ['University of Connecticut','Lousiana State University','Florida State University']
ours1 = yours + mine
print(ours1)
ours2=[]
yours = ['Yale','James Bond College','Berkeley']
ours2.append(yours)
ours2.append(mine)
print(ours2)
yours[1] = 'James Bond College'
print(yours)
#this is just to show it begins at zero, not 1
print(ours1) #still uses MIT#
print(ours2) #Ours2 is dependent on 'Yours' list, so it will change to James Bond College#
print('Ours1 is a stored list that is not affected by the updated. Ours2 is dependent on Yours list, so it will change to James Bond College but Ours1 will not. '
'The change from Yale to J.B.C. comes later in the code and does not affect the Ours1 component lists')
#done
|
4ef010f37e0122f7e417b05f32956ac5e7111fb8 | tpracser/PracserTamas-GF-cuccok | /week-03/day-2/34.py | 262 | 3.546875 | 4 | numbers = [4, 5, 6, 7, 8, 9, 10]
kitties = [4, 5, 6, 7, 8, 9, 11]
# write your own sum function
def sumfunc(num):
a = 0
b = 0
while a < len(num):
b = b + num[a]
a += 1
return (b)
print (sumfunc(numbers))
print (sumfunc(kitties))
|
5aed5bb49e040874e64199f0dad34c9d7b2e79f7 | subodhss23/python_small_problems | /easy_probelms/hiding_card_num.py | 379 | 3.78125 | 4 | ''' Write a function that takes a credit card number and and only displays the
last four characters. The rest of the card number must be replaced by ************.'''
def card_hide(card):
len_of_astrik = len(card) - 4
return '*' * len_of_astrik + card[-4:]
print(card_hide("1234123456785678"))
print(card_hide("8754456321113213"))
print(card_hide("35123413355523")) |
cdcf764fd7e54952858d0f63518606ca83a81791 | SamarthSriv/Sketch_image_using_python | /main.py | 596 | 3.96875 | 4 | # Samarth Srivastava
# 18BCE10232
# Animate your photo using opencv library in python
import cv2
image = cv2.imread("original.jpg") # this will load the image into image variable from root directory
grey_img = cv2.cvtColor(image, cv2.COLOR_BGRA2YUV_YV12) # add grey filter
invert = cv2.bitwise_not(grey_img) # invert colours of our image
blur = cv2.GaussianBlur(invert, (21,21), 0) # blur effect
inverted_blur = cv2.bitwise_not(blur)
sketch = cv2.divide(grey_img, inverted_blur, scale = 256.0)
# save our image file
cv2.imwrite("animated.png", sketch)
# new file named as "animated.png"
|
b4902876438925319b17ef9533d816cd40a538b0 | Tibiazak/4300P3 | /4300PA3.py | 6,576 | 3.578125 | 4 | import random
binary = [0, 1]
pop_size = 5
pop_limit = 81920
string_size = 5
string_list = []
recom_prob = 0.6
# A function that checks the fitness for onemax
def fitness(string):
fit = 0 # initialize accumulator
for c in string: # iterate over every element in the string, increment accumulator for each 1 seen
if c is 1:
fit += 1
return fit # return accumulator (the number of 1's)
# A function that performs binary tournament selection of k = 2 and returns the chosen parent
def selection(population):
s1 = random.choice(population)
s2 = random.choice(population)
# print("Selection 1 is {} and Selection 2 is {}".format(s1, s2))
parent = s1 if (fitness(s1) > fitness(s2)) else s2
return parent
# A function that performs mutation on a string, flipping bits with a probability of 1/N
def mutate(string):
for i in range(0, string_size):
if random.random() < (1/string_size):
string[i] = 1 if (string[i] is 0) else 0
return string
# A function that performs uniform crossover recombination on two strings with given probability
def recombination(p1, p2):
c1 = []
c2 = []
if random.random() > recom_prob: # with 40% probability, copy the parents to the children
# print("Copying the parents to the children\n")
c1 = p1
c2 = p2
else: # with 60% probability, perform recombination
# print("Random recombination\n")
for i in range(0, string_size):
test = random.choice([1, 2]) # randomly choose whether to give parent 1's bit to child 1 or child 2
if test is 1:
c1.append(p1[i])
c2.append(p2[i])
else:
c1.append(p2[i])
c2.append(p1[i])
c1 = mutate(c1) # mutate the children regardless of whether they were copied or recombined
c2 = mutate(c2)
return c1, c2
# A function to get and display stats about the population
def fitness_stats(population):
totalfit = 0
lowestfit = fitness(population[0])
lowindex = 0
highestfit = fitness(population[0])
highindex = 0
for i in range(0, pop_size): # for each element in the population:
currentfit = fitness(population[i]) # get the fitness
totalfit += currentfit # add to our running fitness total
if currentfit < lowestfit: # if its our new low fitness, reflect that
lowestfit = currentfit
lowindex = i
elif currentfit > highestfit: # if its our new high fitness, reflect that
highestfit = currentfit
highindex = i
averagefit = totalfit / pop_size # calculate average fitness
# display statistics
print("The average fitness is {}".format(averagefit))
print("The highest fitness is {} with fitness {}".format(population[highindex], highestfit))
print("The lowest fitness is {} with fitness {}".format(population[lowindex], lowestfit))
return averagefit
# A function to perform replacement - finds the two most fit parents and keeps them, but replaces the rest with children
def replacement(population, child_list):
highest1 = population[0]
highidx1 = 0
fit1 = fitness(highest1)
highest2 = population[1]
highidx2 = 1
fit2 = fitness(highest2)
for index, parent in enumerate(population):
if not ((index is highidx1) or (index is highidx2)):
currentfit = fitness(parent)
if currentfit > fit1:
highest1 = parent
highidx1 = index
elif currentfit > fit2:
highest2 = parent
highidx2 = index
newpop = [highest1, highest2]
# print("The highest fitness parents are: {} at indexes {} and {}".format(newpop, highidx1, highidx2))
for child in child_list:
newpop.append(child)
return newpop
# A function to generate a list of children
def generate_children(population, child_list):
while len(child_list) < (pop_size - 2):
p1 = selection(population)
p2 = selection(population)
c1, c2 = recombination(p1, p2)
child_list.append(c1)
child_list.append(c2)
while len(child_list) > (pop_size - 2):
lowest = child_list[0]
lowfit = fitness(lowest)
for child in child_list:
if fitness(child) < lowfit:
lowest = child
lowfit = fitness(child)
child_list.remove(lowest)
return child_list
# generate random binary strings of pop_size size
def initialize():
for i in range(0, pop_size):
newstring = random.choices(binary, k=string_size)
string_list.append(newstring)
def generational_loop():
global string_list
avgfit = fitness_stats(string_list)
increased = 0
numgens = 0
while increased < 3:
child_list = []
child_list = generate_children(string_list, child_list)
string_list = replacement(string_list, child_list)
newfit = fitness_stats(string_list)
if newfit > avgfit:
# print("Increased")
avgfit = newfit
increased = 0
else:
# print("No increase")
avgfit = newfit
increased += 1
numgens += 1
print("Terminating loop: ")
print("Number of generations taken: {}".format(numgens))
localopt = fitness(string_list[0])
for item in string_list:
if fitness(item) > localopt:
localopt = fitness(item)
return localopt
def overall(popsize, stringsize):
global pop_size
global string_size
pop_size = popsize
string_size = stringsize
initialize()
localopt = generational_loop()
return localopt
stringsize = input("Please enter the desired size of the string: ")
try:
stringsize = int(stringsize)
except ValueError:
print("Error! You must enter a valid integer.")
exit(1)
popsize = 10
while popsize < pop_limit:
index = 0
success = False
while index < 5:
runopt = overall(popsize, stringsize)
print("Run optimum: {}".format(runopt))
if runopt < stringsize:
index = 10
else:
index += 1
if index is 5:
print("Done!")
success = True
break
else:
popsize = 2 * popsize
print("Popsize is now {}".format(popsize))
# TO DO: finish the bisection algorithm, and make the statistics output to a file
# if success:
# upperlimit = popsize
# lowerlimit = popsize/2
# midpoint = (upperlimit - lowerlimit)/2
#
|
b7da965e05bef1196a57117fb94d3b783cf3ffda | anviaggarwal/assignment-2 | /question 6.py | 61 | 3.875 | 4 | r=int(input('enter radius'))
pi=3.14
area=pi*r*r
print(area)
|
d4f4cfd377a43a9b4061b2c776455de7edab9e8b | ang-li7/Kattis | /KitchenMeasurements.py | 343 | 3.625 | 4 | def measurements(cups, goal, tot):
while cups[0]!=goal:
for i in range (1, )
return 0
ss = input().split(" ")
cupss = ss[1:-1]
cups = []
for n in cupss:
cups.append(int(n))
goal = int(ss[-1])
tot = 0
a = measurements(cups, goal, tot)
min = a[0]
for i in a:
if min>i:
min = i
print(i)
#print(cups)
#print(goal) |
27444e932531920fa25ac0c31755fcbb975134b2 | itsolutionscorp/AutoStyle-Clustering | /assignments/python/anagram/src/143.py | 243 | 3.78125 | 4 | def detect_anagrams(str1, str2):
str1_list = list(str1)
str1_list.sort()
for i in str2:
str2_list = list(i)
str2_list.sort()
if str1_list == str2_list:
return i
#detect_anagrams('ant', 'tan stand at'.split())
|
23d9d14145bdaff750519d4b910b883bf20d0695 | shivaniraut5555/sorting-algorithms | /buuble_python.py | 1,187 | 4.0625 | 4 | '''
Bubble sort
Some times reffred as sinking sort,is a simple sorting algorithm which sorts n number of elements in the
list by comparing the each pair of adjacent items and swaps them if they are in wrong order
step1: Starting with the first element (index=0)cpompare the current element wih the next element of the list
step2:If the current element is greater/lesser than the next element of the list swap them
step3:If the current element is less than the next element,move to the next element,repeat step 1
'''
n=int(input("Enter the number of elements:"))#input of elements of list
li=[int(input("Enter elements:")) for x in range(n)]
print("Unsorted list:",li)
#ascending order
for j in range(len(li)-1):
for i in range(len(li)-1):
if li[i]>li[i+1]:
li[i],li[i+1]=li[i+1],li[i] #swapping of number in the list
print(f'The list after {j+1}th iteration:{li}')
print(f'Final sorted list:{li}')
#descdeing order
for j in range(len(li)-1):
for i in range(len(li)-1):
if li[i]<li[i+1]:
li[i],li[i+1]=li[i+1],li[i] #swapping of number in the list
print(f'The list after {j+1}th iteration:{li}')
print(f'Final sorted list:{li}')
|
5793fee8fadee8ed9f0c46d0b8c97d783c0573a5 | plvankam/Fall_2018 | /Object_Oriented/mastering_python/test_env/Circle.py | 369 | 3.625 | 4 | import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def setRadius(self, radius):
self.__radius = radius
def getRadius(self):
return self.__radius
def getArea(self):
return self.__radius * 2 * math.pi
def __add__(self, other):
return Circle(self.__radius + other.getRadius())
|
8ad6fec844040645b7fd76bff5747e1130b2f272 | JessMadok/EstudoPython | /MaquinadeCafe/main.py | 2,496 | 3.828125 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
def report():
print(f"water: {resources['water']}ml")
print(f"milk: {resources['milk']}ml")
print(f"coffee: {resources['coffee']}g")
print(f"money: ${resources['money']}")
def contando_dinheiro (quarter,dime,nickel,penny):
total_quarter = quarter * 0.25
total_dime = dime * 0.10
total_nickel = nickel * 0.05
total_penny = penny * 0.01
total_dinheiro = total_quarter + total_dime + total_nickel + total_penny
return total_dinheiro
def verificando_dinheiro(dinheiro_colocado, custo):
if dinheiro_colocado < custo:
print("Dinheiro insuficiente, tente novamente")
elif dinheiro_colocado > custo:
troco = dinheiro_colocado - custo
print(f"Seu troco é de ${troco}")
resources['money'] += custo
else:
resources['money'] += custo
def meus_recursos (agua, leite, cafe):
if agua > resources['water']:
print("Desculpe não há água o suficiente para o seu pedido")
elif leite > resources['milk']:
print("Desculpe mas não há leite o suficiente para o seu pedido")
elif cafe > resources['coffee']:
print("Desculpe mas não há café suficiente para o seu pedido")
else:
resources['water'] -= agua
resources['milk'] -= leite
resources ['coffee'] -= cafe
tipo_cafe = input("Qual café você gostaria? (espresso/latte/cappuccino) ")
if tipo_cafe == "espresso":
agua = MENU['espresso']['ingredients']['water']
leite = 0
cafe = MENU['espresso']['ingredients']['coffee']
elif tipo_cafe == "latte":
agua = MENU['latte']['ingredients']['water']
leite = MENU['latte']['ingredients']['milk']
cafe = MENU['latte']['ingredients']['coffee']
elif tipo_cafe == "cappuccino":
agua = MENU['cappuccino']['ingredients']['water']
leite = MENU['cappuccino']['ingredients']['milk']
cafe = MENU['cappuccino']['ingredients']['coffee']
elif tipo_cafe == "report":
report()
|
6a9ea1baf5a959622be820c22968f129ddeef2f3 | AlexisDongMariano/miniProjects | /web scraping/price_tracker.py | 2,084 | 3.59375 | 4 | '''
Date: Jun-16-2020
Platform: Windows
Description: [BASIC WEB SCRAPING] - sends an email to the hardcoded recipients
if the item from a shoe shop has dropped its original price
Usage: python price_tracker.py
Sections: A
'''
#SECTION A
import requests
from bs4 import BeautifulSoup
import smtplib
import time
#actual url of the shoe item to be web scraped/monitored
URL = 'https://www.aldoshoes.com/ca/en/men/footwear/casual-shoes/liberace-blue/p/12905197'
def check_price():
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)\
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}
#beautiful soup webscraping initialization
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
price = soup.find(class_='c-product-price__formatted-price').get_text()
item = soup.find(class_='c-heading c-buy-module__product-title').get_text()
converted_price = price[1:]
#run function if the item of the price drops from the original price posted in the site
if float(converted_price) < 70:
send_mail(item, price)
print(converted_price)
print(item)
def send_mail(item, price):
server = smtplib.SMTP('smtp.gmail.com', 587) #specify smtp server, google in our sample
server.ehlo()
server.starttls()
server.ehlo()
server.login('sender_email@gmail.com', 'password') #specify the sender email and password
#compose the email message
subject = 'Aldo Shoe Price Checker'
body = f' Item: {item}\n\
Price: {price}\n\
Check this link: {URL}'
msg = f'Subject: {subject}\n\n{body}'
#list of email recipients
email_addresses = [
'recipient1_email@gmail.com',
'recipient2_email@gmail.com',
'recipient3_email@gmail.com'
]
#send the email to the recipients
for recipient in email_addresses:
server.sendmail(
'sender_email@gmail.com',
recipient,
msg
)
print(f'email sent for {recipient}')
server.quit()
#run the program every hour
while True:
check_price()
time.sleep(60*60)
|
0afd7dd4a54e66ed9a0726654659d2e2f7976129 | kotsurnazariy/HW_soft | /ClassWork1.py | 1,373 | 3.765625 | 4 | #1
# a = 0
# while a < 100:
# print (a)
# a += 2
# a = 0
# for a in range(0, 100, 2):
# print(a)
#2
# a = 1
# while a < 100:
# print(a)
# a += 2
# a = 1
# for a in range(100):
# if a % 2 == 0:
# continue
# print(a, end=' ')
#3
# a = [2, 4, 6, 7, 10]
# for a in a:
# if a % 2 == 1:
# print('This list have odd number', a)
# break
# else:
# print('This even number:', a)
#4
# my_list = [1, 2, 3, 4, 5]
# i = 0
# for my_list[i] in my_list:
# b_len = float(my_list[i])
# print(b_len)
# i += 1
#5
# n = input("Enter any-thing number: ")
# n = int(n)
# fib_1 = 0
# fib_2 = 1
# print(fib_1)
# while fib_2 <= n:
# temp = fib_2
# fib_2 = fib_1 + fib_2
# fib_1 = temp
# print(temp)
#6
# my_list = ['one', 'two', 'three', 'four']
# i = 0
# for my_list[i] in my_list:
# print(my_list[i])
# i += 1
#7
# my_list = ['one', 'two', 'three', 'four']
# i = 0
# a = 0
# for my_list[i] in my_list:
# for a in my_list[i]:
# print(a, end="#")
# i += 1
#8
#9
# import random
# num_rund = random.randint(100, 1000)
# print(num_rund)
# list_rund = list(str(num_rund))
# print(list_rund)
# print(max(list_rund))
#10
# word = input('Enter word: ')
# word_polin = word[::-1]
# if word == word_polin:
# print('Polinom:', word)
# else:
# print("Not polinom:", word) |
fb08e7693738cda1393834ca5d305d0fe7b5a9ea | VaibhavD143/Coding | /leet_letter_combination_phone_number.py | 246 | 3.5 | 4 | dic = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
n = "234"
res = list(dic[n[0]])
for i in range(1,len(n)):
res = [res[j]+dic[n[i]][k] for k in range(len(dic[n[i]])) for j in range(len(res))]
print(res) |
678ae7d5cef48663509c8a5a58636a86cc736d52 | Pshypher/tpocup | /ch06/projects/proj_02b.py | 1,773 | 4.5625 | 5 | # Program designed for the purposes of substring matching with applications
# in genetics, such as trying to find a substring of bases ACTG
# (adenine, cytosine, thymine and guanine) in a known DNA string, or
# reconstructing an unknown DNA string from pieces of nucleotide bases
# Unless stated otherwise,all variables are of the type int
# Without using the string method find, a custom function that finds the lowest
# index that a substring occurs within a string is defined
def find(some_string, substring, start, end):
"""Returns the lowest index where a substring is first found occuring
within a larger string or -1 if the substring is not contained within
the string."""
if end > len(some_string):
end = len(some_string)
index = start
while len(some_string[index:]) >= len(substring) and index < end:
if some_string[index:index + len(substring)] != substring:
index = index + 1
else:
break
else:
index = -1
return index
# The subsequent function defined below finds all the locations where a
# substring is found, not simply the first one within a larger string
def multi_find(some_string, substring, start, end):
"""Returns a string containing all the indices of all the occurences of
a substring within a larger string. An empty string is returned if the
string contains no such occurence of the substring."""
indices_str = ""
index = start
while index != -1:
index = find(some_string, substring, index, end)
if index != -1:
indices_str = indices_str + str(index) + ', '
index += 1
else:
indices_str = indices_str[:-2]
return indices_str
|
0dc95f2b65992865eb9c38062a7acb8fd68d5278 | alsbhn/CityAnnotation_App | /database.py | 1,817 | 3.703125 | 4 | import os
import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine("sqlite:////database.db") # database engine object from SQLAlchemy that manages connections to the database
# DATABASE_URL is an environment variable that indicates where the database lives
db = scoped_session(sessionmaker(bind=engine)) # create a 'scoped session' that ensures different users' interactions with the
#f = open("googlenews_top_monthly_2019_45cities_text_6.csv")
#reader = csv.reader(f)
#for ID, city, month, url, text, title, summary, keywords in reader: # loop gives each column a name
db.execute("INSERT INTO googlenews (ID, city, month, url, text, title, summaty, keywords) VALUES (:ID, :city, :month, :url, :text, :title, :summaty, :keywords)",
{"ID": ID, "city": city, "month": month, "url": url, "text": text, "title": title, "summary": summary, "keywords": keywords}) # substitute values from CSV line into SQL command, as per this dict
print(f"Added news about {city} in month {month}.")
db.commit() # transactions are assumed, so close the transaction finished
db.execute("INSERT INTO newtable (name, id) VALUES (:name, :id)",
{"name": 'ali2', "id": 26})
db.commit() # database are kept separate
#db.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
#db.commit()
#flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall() # execute this SQL command and return all of the results
#for flight in flights:
# print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.") # for every flight, print out the flight info
|
4ecd7b72fd7bee1795002abd85f026ca2bed74f3 | SeitzhagyparovaTE/web | /week_7/1.Informatics/1.3_Loops/1.3.1_For/C.py | 151 | 4.09375 | 4 | import math
for number in range(int(input()), int(input()) + 1, 1):
if int(math.sqrt(number)) ** 2 == int(number):
print(number, end = " ") |
9cf9f7e1f6236f559c282683dce320429c9ac261 | euclude/PythonFinance | /sim/MarketSimulator.py | 4,714 | 3.59375 | 4 | import pandas as pd
from finance.utils import DataAccess
from datetime import datetime
class MarketSimulator(object):
'''
Market Simulator.
Receives:
1. Initial cash
2. List of trades (automaticly search and downloads missing information)
After simulation:
portfolio is a pandas.DataFrame with the values of the portfolio on each date
'''
def __init__(self, path='./data'):
self.da = DataAccess(path)
self.initial_cash = 0
self.current_cash = 0
self.trades = None
self.prices = None
self.own = None
self.cash = None
self.equities = None
self.portfolio = None
def load_trades(self, file_path):
'''
Reads the csv file and parse the data
'''
# 1. Read the .csv file
self.trades = pd.read_csv(file_path)
# 2. Set the indexes as the value of a the columns (year, month, day)
dates = list()
for idx, row in self.trades.iterrows():
date = datetime(row['year'], row['month'], row['day'])
dates.append(date)
dates = pd.Series(dates)
self.trades = self.trades.set_index(dates)
# 3. Delete unnescessary columns
self.trades = self.trades[['symbol', 'action', 'num_of_shares']]
# 4. Sort the DataFrame by the index (dates)
self.trades = self.trades.sort()
def simulate(self, trades=None, ordersIsDataFrame=False):
'''
Simulates the trades, fills the DataFrames: cash, equities_value, porfolio
'''
# 0. Init the required data
# 0.1 if trades is not None load them
if trades is not None:
if ordersIsDataFrame:
self.set_trades(trades)
else:
# If there is no DataFrame then is a file to be loaded
self.load_trades(trades)
# 0.2 Load/Download required data
symbols = list(set(self.trades['symbol']))
start_date = self.trades.index[0].to_pydatetime() # Convert from TimeStamp to datetime
end_date = self.trades.index[-1].to_pydatetime()
self.prices = self.da.get_data(symbols, start_date, end_date, "Adj Close")
# 0.3 Init other DataFrames, dictionaries
self.cash = pd.DataFrame(index=self.prices.index, columns=['Cash'])
self.own = pd.DataFrame(index=self.prices.index, columns=self.prices.columns)
current_stocks = dict([(symbol, 0) for symbol in list(set(self.trades['symbol']))])
# 0.3 Set the current cash to the initial cash before star the simulation
self.current_cash = self.initial_cash
# 1. Fill the DataFrames
for idx, row in self.trades.iterrows():
# For each order
# Note: idx is Timestamp, row is Series
# Note 2: If there are various trades on the same day overwrites the previous value.
# 1.0 Get info of the row
symbol = row['symbol']
action = row['action'].lower()[0:1]
num_of_shares = row['num_of_shares']
# 1.1 Fill the cash DataFrame
# Get the change of cash on the order
cash_change = self.prices[symbol][idx] * num_of_shares
if action == 'b':
self.current_cash = self.current_cash - cash_change
elif action == 's':
self.current_cash = self.current_cash + cash_change
# Modify self.cash DataFrame
self.cash.ix[idx] = self.current_cash
# 1.2 Fill the own DataFrame - num of stocks on each date
if action == 'b':
current_stocks[symbol] = current_stocks[symbol] + num_of_shares
elif action == 's':
current_stocks[symbol] = current_stocks[symbol] - num_of_shares
# Modify self.own DataFrame
self.own.ix[idx][symbol] = current_stocks[symbol]
# Fill forward missing values
self.cash = self.cash.fillna(method='ffill')
self.own = self.own.fillna(method='ffill')
# After forward-fill fill with zeros because initial values are still NaN
self.own = self.own.fillna(0)
# 2. Get the value of the equitues
self.equities = self.own * self.prices
self.equities = self.equities.sum(1)
# 3. Get the value of the porfolio = cash + equities_value
self.portfolio = self.cash + self.equities
self.portfolio.columns = ['Portfolio']
if __name__ == "__main__":
sim = MarketSimulator('./test/data2')
sim.initial_cash = 1000000
sim.load_trades("../examples/MarketSimulator_orders.csv")
sim.simulate()
print(sim.portfolio.tail())
|
31d32802f4cb2c99ee507ffe1f964770ace43a2e | alsomilo/leetcode | /0023-merge-k-sorted-lists/0023-merge-k-sorted-lists.py | 1,879 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
'''
def mergTwo(l1, l2):
if None in (l1, l2):
return l1 or l2
curr = dummy = ListNode()
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
curr, l1 = curr.next, l1.next
else:
curr.next = l2
curr, l2 = curr.next, l2.next
curr.next = l1 or l2
return dummy.next
if not lists:
return None
if len(lists) == 1:
return lists[0]
res = lists[0]
for i in range(1, len(lists)):
res = mergTwo(res, lists[i])
return res
'''
def mergTwo(l1, l2):
if None in (l1, l2):
return l1 or l2
curr = dummy = ListNode()
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
curr, l1 = curr.next, l1.next
else:
curr.next = l2
curr, l2 = curr.next, l2.next
curr.next = l1 or l2
return dummy.next
if not lists:
return None
if len(lists) == 1:
return lists[0]
if len(lists) == 2:
return mergTwo(lists[0], lists[1])
split = len(lists)//2
return mergTwo(self.mergeKLists(lists[:split]), self.mergeKLists(lists[split:])) |
8146b6579d56606d78c2c9727801ea69d3d2522a | heenach12/pythonpractice | /Stack/stack_using_linkedlist.py | 1,281 | 3.90625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self, value):
self.head = Node("head")
self.size = 0
def __str__(self):
cur = self.head.next
out = ""
while(cur):
out += str(cur.value) + "->"
cur = cur.next
return out[:-3]
def isEmpty(self):
return self.size == 0
def getSize(self):
return self.size
def peek(self):
if self.isEmpty():
raise Exception("Popping from empty stack")
return self.head.next.value
def push(self, v):
node = Node(v)
node.next = self.head.next
self.head.next = node
self.size += 1
def pop(self):
if self.isEmpty():
raise Exception("Popping from empty stack")
r = self.head.next
self.head.next = self.head.next.next
self.size -=1
return r.value
t = int(input())
for i in range(t):
n = int(input())
s = Stack()
a = list(map(int, input().strip().split()))
i = 0
while (i < len(a)):
if a[i] == 1:
s.push(a[i + 1])
i += 2
elif a[i] == 2:
print(s.pop(), end=" ")
i += 1
|
1c7bec2280216c57985c2c893adf618e48617eb5 | dstada/HackerRank.com | /Happy Ladybugs.py | 1,185 | 3.859375 | 4 | def check_happy(b):
overall_happy = True
for i in range(len(b)):
happy = False
# If left or right is the same colour bug, then happy:
if (i - 1 >= 0 and b[i - 1] == b[i]) or i + 1 < len(b) and b[i + 1] == b[i]:
happy = True
else:
overall_happy = False
return overall_happy
def happyLadybugs(b):
# At least one char is the only of that kind:
for letter in b:
if letter != '_' and b.count(letter) < 2:
return "NO"
# Check if existing ladybugs are happy now:
if check_happy(b) is True:
return "YES"
else:
if b.count("_") == 0:
for i in range(1, n - 1):
if b[i - 1] != b[i] and b[i + 1] != b[i]: # No similar neighbours
return "NO"
return "YES" # Empty place(s)
if __name__ == '__main__':
g = int(input())
for g_itr in range(g):
n = int(input())
b = input()
result = happyLadybugs(b)
print(result)
"""
Input:
5
5
AABBC
7
AABBC_C
1
_
10
DD__FQ_QQF
6
AABCBC
Output:
NO
YES
YES
YES
NO
https://www.hackerrank.com/challenges/happy-ladybugs/problem
""" |
427bdedcdc4618277388ab98b37e80eb6b2e1ee1 | iandioch/solutions | /advent_of_code/2021/12/part2.py | 1,066 | 3.765625 | 4 | import sys
from collections import defaultdict, deque
def can_move(path, other, is_small):
if other == 'start':
return False
if not is_small[other]:
return True
if other not in path:
return True
d = defaultdict(int)
for p in path:
if not is_small[p]:
continue
d[p] += 1
for e in d:
if d[e] > 1:
return False
return True
def count_paths(d, is_small):
q = deque()
q.append(('start', ['start']))
finish = set()
while len(q):
pos, path = q.popleft()
if pos == 'end':
finish.add('-'.join(path))
continue
for other in d[pos]:
if can_move(path, other, is_small):
q.append((other, path[:] + [other]))
return len(finish)
def main():
d = defaultdict(list)
for line in sys.stdin.readlines():
a, b = line.strip().split('-')
d[a].append(b)
d[b].append(a)
is_small = {c:(c.lower() == c) for c in d}
print(count_paths(d, is_small))
main()
|
c015318b470117603990bbf7e5c2eaa0835e0ad3 | DredNaut/Python-Unittest | /linked_list.py | 1,245 | 3.90625 | 4 | from node import Node
class LinkedList():
def __init__(self):
self.list = None
def get_head(self):
if self.is_empty():
return None
else:
return self.list
def is_empty(self):
return True if (self.list == None) else False
def get_last_node(self):
if self.is_empty():
return None
else:
node = self.list
while node.get_next() != None:
node = node.get_next()
return node
def append(self,value):
if self.is_empty():
self.list = Node()
self.list.set_value(value)
return True
else:
new = Node()
new.set_value(value)
self.get_last_node().set_next(new)
return True
def remove(self,value):
if self.is_empty():
return False
else:
node = self.list
last = Node()
while node.get_value() != value:
if node.get_next() == None:
return False
last = node
node = node.get_next()
last.set_next(node.get_next())
del node
return True
|
403d7d3f1386a821c277306d90af65b799b5717b | kmsmgsh/python | /Metropolis.py | 2,104 | 3.90625 | 4 | import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class Metropolis:
def __init__(self,IterNa,density,initial,sigma):
self.IterNa=IterNa
self.density=density
self.initial=initial
self.Mainprocess(sigma)
def printAll(self):
print("Number of Iterative is")
print(self.IterNa)
print("Initial Value of Metropolis is")
print(self.initial)
print("initial pdf value of f")
print(self.density(self.initial))
print(self.density)
print("Accept rate")
print(self.accept/self.IterNa)
def Mainprocess(self,sigma):
'''
This is the random walk metropolis hastings with the random walk using normal distribution
N(theta,sigma)
The problem is how to get the Sigma so that the accept rate is around 44%
'''
'''
Maybe need a function to handle the multi-variable occasion
This just for 1-Dimension
'''
theta=self.initial
record=np.array(theta)
accept=0
for i in range(self.IterNa):
theta_star=np.exp(np.random.normal(np.log(theta), sigma))
'''
what is the random walk come out of the define interval
'''
#Accept the new beta value with the probability f(beta_start)/f(beta)
p=min(self.density(theta_star)/self.density(theta),1)####################Transfor p/p,or use log normal
if np.random.uniform(0,1)<p:
#Accept the new Value
theta=theta_star
#count the number of accept
accept+=1
#add to record
record=np.append(record,theta)
self.record=record
self.accept=accept
def showplot(self):
plt.plot(range(self.IterNa+1),self.record)
plt.show()
plt.hist(self.record,bins=50)
plt.show()
'''
Test code
sample=Metropolis(1000,norm.pdf,0)
sample.printAll()
print(sample.record)
sample.showplot()
''' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.