blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
16ef7625d209909e66693475626eda6fd76c6e64 | adwardlee/leetcode_solutions | /hash&heap/0129_lint_Rehashing.py | 2,680 | 4.34375 | 4 | '''
Description
The size of the hash table is not determinate at the very beginning. If the total size of keys is too large (e.g. size = capacity 10), we should double the size of the hash table and rehash every keys. Say you have a hash table looks like below
size=3, capacity=4
[null, 21, 14, null]
↓ ↓
9 null
↓
null
The hash function is
int hashcode(int key, int capacity) {
return key % capacity;
}
here we have three numbers, 9, 14 and 21, where 21 and 9 share the same position as they all have the same hashcode 1 (21 % 4 = 9 % 4 = 1). We store them in the hash table by linked list.
rehashing this hash table, double the capacity, you will get
size=3, capacity=8
index 0 1 2 3 4 5 6 7
hash [null, 9, null, null, null, 21, 14, null]
Given the original hash table, return the new hash table after rehashing .
For negative integer in hash table, the position can be calculated as follow
C++Java if you directly calculate -4 % 3 you will get -1. You can use function a % b = (a % b + b) % b to make it is a non negative integer.
Python you can directly use -1 % 3, you will get 2 automatically.
Example
Example 1
Input [null, 21-9-null, 14-null, null]
Output [null, 9-null, null, null, null, 21-null, 14-nul
'''
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param hashTable: A list of The first node of linked list
@return: A list of The first node of linked list which have twice size
"""
def rehashing(self, hashTable):
# write your code here
capacity = len(hashTable)
newcapacity = 2 * capacity
newhashTable = []
for i in range(newcapacity):
newhashTable.append(None)
for onenode in hashTable:
while onenode != None:
val = onenode.val
new_index = self.hash_function(val, newcapacity)
if newhashTable[new_index] == None:
newhashTable[new_index] = ListNode(val)
else:
tmp = newhashTable[new_index]
while tmp.next != None:
tmp = tmp.next
tmp.next = ListNode(val)
#tmp = newhashTable[new_index].next
#newhashTable[new_index].next = ListNode(val)
#newhashTable[new_index].next.next = tmp
onenode = onenode.next
return newhashTable
def hash_function(self, val, capacity):
return (val % capacity + capacity) % capacity |
7f5958f2814e5ae68902a21db0fc09902a4c821e | juansalvatore/algoritmos-1 | /prueba_parcial/ultimo_parcial/1.py | 499 | 4.03125 | 4 | # 2) Escribir una funcion recursiva que reciba una lista y un parametro n, y devuelva otra
# lista con los elementos de la lista replicados esa cantidad n de veces.
# Por ejemplo, replicar ([1, 3, 3, 7], 2) debe devolver ([1, 1, 3, 3, 3, 3, 7, 7]) .
def replicar(lista, n):
nueva_lista = []
if len(lista) == 0:
return lista
else:
nueva_lista += lista[:1] * n
return nueva_lista + replicar(lista[1:], n)
lista = [1, 3, 3, 7]
print(replicar(lista, 2))
print(lista)
|
2b190e5d8945b779f243094e3a11a05354bd8f82 | NagahShinawy/100-days-of-code | /day_1/varaibles.py | 352 | 3.515625 | 4 | from constant import DIE_DICE, UNDER_AGE
from die_dice import Number
number = Number(2)
# number = Number("4")
# is_valid = number.is_valid()
num = number.to_int()
num_as_literal = DIE_DICE[num]
print(num, num_as_literal)
print(number.is_odd())
print(number.is_even())
if num < UNDER_AGE:
print("Age is under age")
else:
print("Accepted")
|
917bc6041b15f93e55dab419d5a074fe71adeca2 | jashidsany/Learning-Python | /Codecademy Lesson 6 Strings/LA6.10_Strings_And_Conditionals_2.py | 1,196 | 4.5625 | 5 | # We can iterate through a string using in
# The syntax for in is: letter in word
# Here, letter in word is a boolean expression that is True if the string letter is in the string word. Here are some examples:
print("e" in "blueberry")
# => True
print("a" in "blueberry")
# => False
# In fact, this method is more powerful than the function you wrote in the last exercise because it not only works with letters, but with entire strings as well.
print("blue" in "blueberry")
# => True
print("blue" in "strawberry")
# => False
# This function checks if the little string is in the big string
def contains(big_string, little_string):
if little_string in big_string:
return True
else:
return False
print(contains('watermelon', 'melon'))
print(contains('watermelon', 'berry'))
def common_letters(string_one, string_two):
common = []
for letter in string_one:
# iterate through the letters in string_one
if (letter in string_two) and not (letter in common):
# if letter is in string_two and not in the list of common append it
common.append(letter)
return common
print(common_letters('manhattan', 'san francisco'))
|
cb9867ceb042e3d4069edfa99a8ca04d4f1ec1e6 | poojithayadavalli/codekata | /longest consecutive sub sequence.py | 748 | 3.546875 | 4 | def findLongestConseqSubseq(arr, n):
x={}
s=set(x)
ans=0
# Hash all the array elements
for ele in arr:
s.add(ele)
# check each possible sequence from the start
# then update optimal length
for i in range(n):
# if current element is the starting
# element of a sequence
if (arr[i]-1) not in s:
# Then check for next elements in the
# sequence
j=arr[i]
while(j in s):
j+=1
# update optimal length if this length
# is more
ans=max(ans, j-arr[i])
return ans
n=int(input())
arr=list(map(int,input().split()))
print(findLongestConseqSubseq(arr, n))
|
27c27346a4e5e2f6adfc8b77a2d65b0b851f56ec | CTEC-121-Spring-2020/mod-5-programming-assignment-Brandon-Clark189 | /Prob-3/Prob-3.py | 1,262 | 4.125 | 4 | # Module 4
# Programming Assignment 5
# Prob-3.py
# Brandon Norton
# Input: Square feet of wall space, cost of gallons of paint
# process: calculate estimate of hours and cost of job
# Output: Prints estimate of hours, and cost of job
# function definition
from math import *
# main function definition
def estimate(squareFeet, costofPaint):
hours =ceil((squareFeet / 112) * 8)
gallons = ceil((squareFeet / 112) * 1)
print("Hours of labor required:", hours, "hours")
print("Gallons of paint needed:", gallons, "gallons")
print("Square feet of job:", squareFeet, "square feet")
print("Cost of paint per gallon: $",costofPaint)
costofLabor = hours * 35.00
print("Labor costs: $", costofLabor)
paintCost = gallons * costofPaint
print("Total cost of paint $", paintCost)
totalCost = costofLabor + paintCost + 99.00
print("Setup fee: $99")
print("Total cost of job: $", totalCost)
def main():
squareFeet = eval(input("Please input number of square feet for job: "))
costofPaint = eval(input("Please input cost of paint: "))
print()
estimate(squareFeet, costofPaint)
'''
print("Test 1")
estimate(300, 10)
print()
print("Test 2")
estimate(562, 28.50)
'''
main()
|
8d3b0e82a785305f90e1bc09fd0bdfc027f336f0 | kah3f/python_example_solutions | /filestats.py | 1,682 | 3.5625 | 4 | import string
class Wordstats:
def __init__(self,filename):
try:
fin=open(filename,'r')
except IOError:
print "Unable to open file %s"%filename
return None
ignore=['the', 'of', 'and', 'to', 'a', 'in', 'be','been', 'it', 'by', 'if', 'that', 'or', 'for', 'which', 'this', 'an', 'all', 'its', 'not', 'with', 'their','they','them','me','my', 'is', 'as', 'from', 'may', 'i', 'on', 'but', 'can', 'only', 'his','her','our','there','here','what','when','where','by','be','is','are','have','has','had','he','she','no','we','us','you','your','these','those','was','were','above','below','behind','beneath','before','after','upon','under','between','through','at','any','all','so','than']
self.counts = {}
for line in fin:
words=line.split()
for word in words:
word=word.lower().strip(string.punctuation)
if word in ignore:
continue
elif word not in self.counts:
self.counts[word] = 1
else:
self.counts[word] += 1
def number_unique(self):
return len(self.counts)
def frequencies(self,N=0):
if N==0:
return sorted(self.counts,key=self.counts.get,reverse=True)
else:
return sorted(self.counts,key=self.counts.get,reverse=True)[:N]
def match_words(self,compare):
match_list=[]
for word in compare:
if word in self.counts:
match_list.append(word)
return (match_list,len(match_list))
def histogram(self,N):
freq_list=self.frequencies(N)
for word in freq_list:
self.counts[word]
|
a5e6c14e03fc9acef8372d8eb30cf608f1e9fcf5 | petervdonovan/ArticlesProc | /ArticlesProc/StatsAndVisualization/Difference.py | 4,499 | 3.90625 | 4 | from StatsAndVisualization.visualizationUtils import zScoreToRGB
import math
from scipy import stats
class Difference(object):
"""Class representation a difference between samples,
described in terms of what it signifies about a difference
between populations."""
def __init__(self, testStatistic, significanceLevels):
'''Initialize based on calculated values. Significance levels are
pairs, where the first element is alpha and the second element is a
boolean representing whether the statistic is significant at that
alpha level.'''
#print('hello, i am a difference and my test statistic is', testStatistic)
self.testStatistic = testStatistic
'''The test statistic (e.g., t, z)'''
self.significanceLevels = {}
for significanceLevel in significanceLevels:
self.significanceLevels[significanceLevel[0]] = significanceLevel[1]
# Factory methods
@classmethod
def comparePopulationMean(cls, series1, series2, *alphas):
'''Returns -1 if series1 appears to have a lower mean,
+1 if series1 appears to have a higher mean,
and 0 if it is not possible to reject the possibility that the
population mean is the same.'''
n1 = series1.size
n2 = series2.size
if n1 <= 0 or n2 <= 0:
return 0
xBar1 = series1.mean()
xBar2 = series2.mean()
return propComparePopulationMean(cls, n1, n2, xBar1, xBar2, sigma1, sigma2, alphas)
@classmethod
def propComparePopulationMean(cls, n1, n2, xBar1, xBar2, s1, s2, alphas):
if s1 is None or s2 is None or not n1 or not n2:
return cls(None, [])
a = s1*s1/n1
b = s2*s2/n2
t = (xBar1 - xBar2)/(math.sqrt(a + b))
df = (a+b)*(a+b)/(a*a/(n1-1) + b*b/(n2-1))
significanceLevels = []
for alpha in alphas:
if df and df > 0:
tSubAlphaOverTwo = stats.t.ppf(1 - alpha/2, df)
significanceLevels.append((alpha, abs(t) > tSubAlphaOverTwo))
#print(t)
#print('t is no!', t, n1, n2, xBar1, xBar2, s1, s2, alphas)
return cls(t, significanceLevels)
def __float__(self):
return float(self.testStatistic)
def __str__(self):
return str(self.testStatistic)
def getSignificance(self, alpha):
'''Returns whether this Difference is known to be statistically
significant for a given alpha value. Returns false if the answer
cannot be determined, given the information with which the
Difference was initialized.'''
for level in self.significanceLevels:
if level <= alpha and self.significanceLevels[level] == True:
return True
return False
def getStat(self):
'''Returns the test statistic of this Difference.'''
return self.testStatistic
@staticmethod
def testStatAsHSL(difference):
'''Returns an HSL value in the form of a CSS rule based on the
test statistic.'''
if not isinstance(difference, Difference) or difference.getStat() is None or math.isnan(difference.getStat()):
return ''
if not difference:
return zScoreToRGB(0)
return 'background-color: ' + zScoreToRGB(difference.getStat()) + ';'
@staticmethod
def formatBasedOnSignificance(difference):
'''Returns a CSS rule based on the significance level.'''
if not isinstance(difference, Difference) or difference.getStat() is None or math.isnan(difference.getStat()):
return ''
if not difference:
return ''
rule = ''
if difference.getSignificance(0.05):
rule += 'font-weight: bold;'
if difference.getSignificance(0.01):
rule += 'font-style: italic;'
return rule
def getInverted(self):
testStatistic = self.testStatistic
significanceLevels = [(level, self.significanceLevels[level])
for level in self.significanceLevels]
return Difference(-testStatistic, significanceLevels)
# Supporting methods
def putDifferencesToExcel(writer, sheetName, chart):
'''Puts a conditionally formatted description of the differences in subset means to an Excel sheet.'''
styler = chart.round(2).style
styler.applymap(Difference.testStatAsHSL).applymap(Difference.formatBasedOnSignificance)
styler.to_excel(writer, sheet_name=sheetName) |
d6c1ddd88886c4d13754ba3e32223daca7648c89 | mitarai1kyoshi/Python_learning | /ch01-02.py | 322 | 3.921875 | 4 | #变量 数据类型
name = 'Hello Python ' #//f: ,cd pwork ,python 1.py
print(name.upper())#不改变name值 print(name.lower())
name_modified=name.rstrip()#去除末尾多余的空白,也可以用lstrip,strip去除开头和两端的空白
age=18
message="happy "+str(age)+"th birthday" #int to string
print(message) |
421c091f433be6f8f601b82e8ec6e229a64e309d | kh4r00n/SoulCodeLP | /sclp040.py | 275 | 3.953125 | 4 | #7) Faça um programa que leia 5 idades e mostre na tela a média das idades lidas.
cont = 1
soma = 0
while cont <= 5:
idade = int(input('informe a sua idade: '))
soma += idade
cont += 1
media = soma / 5
print(f'A média das idades é igual a: {media}') |
47855cdc6308905b15202548fe1fd5eb6beb1424 | aichiko0225/Python_review | /review/review.py | 7,694 | 4.0625 | 4 |
from collections import Iterable, Iterator
import os
# 高等特性
# 1. 切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L1 = L[0:3]
print(L1)
# 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环:
r = []
n = 3
for i in range(n):
r.append(L[i])
print(r)
# L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。
# 如果第一个索引是0,还可以省略:
L[:3]
L2 = list(range(100))
L2[-10:]
# 前10个数,每两个取一个:
l1 = L2[:10:2]
print(l1)
# 所有数,每5个取一个:
l2 = L2[::5]
print(l2)
# 甚至什么都不写,只写[:]就可以原样复制一个list:
l3 = L2[:]
print(l3)
# tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
T = (1, 3, 4, 5, 6, 6, 7)
t1 = T[:3]
print(t1)
# 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:
str1 = 'ABCDEFG'
str2 = str1[:3]
print(str2)
str3 = str1[::2]
print(str3)
# 2. 迭代
# 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。
# 所以,当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。
# list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代:
# 由于字符串也是可迭代对象,因此,也可以作用于for循环:
# 那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
bool1 = isinstance('abc', Iterable)
print(bool1)
# 最后一个小问题,如果要对list实现类似Java那样的下标循环怎么办?
# Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
for x, y in [(1, 3), (2, 4), (5, 6)]:
print(x, y)
# 3. 列表生成式
# 列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
# 写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来,十分有用,多写几次,很快就可以熟悉这种语法。
com = [x * x for x in range(1, 10)]
print(com)
# for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:
com1 = [x * x for x in range(1, 10) if x % 2 == 0]
print(com1)
# 还可以使用两层循环,可以生成全排列:
com2 = [m + n for m in 'ABC' for n in 'XYZ']
print(com2)
# 运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现:
com3 = [d for d in os.listdir('.')]
print(com3)
# 列表生成式也可以使用两个变量来生成list:
dic = {'x': 'A', 'y': 'B', 'z': 'C'}
com4 = [k+' = '+v for k, v in dic.items()]
print(com4)
# 最后把一个list中所有的字符串变成小写:
com5 = [v.lower() for v in ['Hello', 'World', 'IBM', 'Apple'] if isinstance(v, str)]
l4 = ['Hello', 'World', 18, 'Apple', None]
print([s.lower() if isinstance(s, str) else s for s in l4])
print(com5)
# 4. 生成器
# 通过列表生成式,我们可以直接创建一个列表。
# 但是,受到内存限制,列表容量肯定是有限的。
# 而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
# 所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?
# 这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
# 要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
generator1 = (x * x for x in range(1, 10))
print(generator1)
# 我们讲过,generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。
for n in generator1:
print(n)
def fib(max: int):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n += 1
return 'done'
f = fib(6)
print(f)
# 这里,最难理解的就是generator和函数的执行流程不一样。
# 函数是顺序执行,遇到return语句或者最后一行函数语句就返回。
# 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
# 但是用for循环调用generator时,发现拿不到generator的return语句的返回值。
# 如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:
while True:
try:
x = next(f)
print('g:', x)
except StopIteration as identifier:
print('Generator return value:', identifier.value)
break
# generator是非常强大的工具,在Python中,可以简单地把列表生成式改成generator,也可以通过函数实现复杂逻辑的generator。
# 要理解generator的工作原理,它是在for循环的过程中不断计算出下一个元素,并在适当的条件结束for循环。
# 对于函数改成的generator来说,遇到return语句或者执行到函数体最后一行语句,就是结束generator的指令,for循环随之结束。
# 5. 迭代器
# 我们已经知道,可以直接作用于for循环的数据类型有以下几种:
# 一类是集合数据类型,如list、tuple、dict、set、str等;
# 一类是generator,包括生成器和带yield的generator function。
# 这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
# 可以使用isinstance()判断一个对象是否是Iterable对象:
# 生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出StopIteration错误表示无法继续返回下一个值了。
# 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
# 可以使用isinstance()判断一个对象是否是Iterator对象:
isinstance(f, Iterator)
# 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
# 把list、dict、str等Iterable变成Iterator可以使用iter()函数:
isinstance(iter([]), Iterator)
# 你可能会问,为什么list、dict、str等数据类型不是Iterator?
# 这是因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。
# 可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据,
# 所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。
# Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
|
9037371df54a238a0115ce69f7dd8ec65d13f07f | bonnieyan/Python | /gemstone.py | 683 | 3.53125 | 4 | # 复杂度是较高
def numJewelsInStones(J, S):
J_length = len(J)
S_length = len(S)
if J_length > 50 or S_length > 50:
print("字符长度超长")
count = 0
for s in S:
if s in J:
count = count + 1
return count
print(numJewelsInStones("ba", "aAAbbbb"))
# 复杂度O(n)
def numJewelsInStones(J, S):
stores = {}
for c in S:
if c in stores:
stores[c] = stores[c] + 1
else:
stores[c] = 1
count = 0
for c in J:
if c in stores:
count += stores[c]
print(count)
J = "aA"
S = "aAAbbbb"
numJewelsInStones(J, S)
J = "z"
S = "ZZ"
numJewelsInStones(J, S)
|
bd5583489e640b4dbe0b19cfd65b64551b35e750 | thenickforero/holbertonschool-machine_learning | /math/0x02-calculus/9-sum_total.py | 479 | 4.09375 | 4 | #!/usr/bin/env python3
"""Module to calculate sums of i*i.
"""
def summation_i_squared(n):
"""Compute the summation of i squared (i²)
by using the Faulhaber's formula.
Arguments:
n (int): the index or the limit of the summation.
Returns:
int: the summattion if the limit is valid, else None.
"""
if not isinstance(n, (int, float)) or n < 1:
return None
a = 2 * (n ** 3)
b = 3 * (n ** 2)
return int((a + b + n) / 6)
|
e3739e2426ed3c909e713d3b796d9a4803016b34 | ShayanRiyaz/Data-Visualization-basics | /2_CSV-File-Format/sitka_highs.py | 1,114 | 3.640625 | 4 | import csv
import matplotlib.pyplot as plt
from datetime import datetime
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# Get dates, high and low temperatures from this file.
dates, highs,lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2],'%Y-%m-%d')
high = int(row[5])
low = int(row[6])
dates.append(current_date)
highs.append(high)
lows.append(low)
# Plot the high temperatures.
plt.style.use('seaborn')
fig,ax = plt.subplots()
ax.plot(dates,highs,c='red')
ax.plot(dates,lows,c = 'blue')
plt.fill_between(dates,highs,lows,facecolor = 'green', alpha = 0.2)
# Format plot.
plt.title("Daily High and Low Temperatures, 2018", fontsize = 24)
plt.xlabel('',fontsize = 16)
plt.ylabel("Temperatures (F)",fontsize = 16)
fig.autofmt_xdate()
plt.tick_params(axis = 'both',which = 'major', labelsize = 16)
plt.show() |
580c9c5fa9b21d3285c2dad01f55fc9aff5cde07 | Abhay-official/Summer-Training | /Day08/Day8J.py | 1,580 | 3.75 | 4 | x=set('A Python Tutorial')
print(x)
print(type(x))
x=set(['Perl','Python','Java'])
print(x)
cities=set(('Paris','Lyon','London','Berlin','Paris','Birmingham'))
print(cities)
#cities=set(('Python','Perl'),('Paris','Berlin','London'))
print(cities)
cities=set(['Frankfurt','Basel','Freiburg'])
print(cities)
cities.add('Strasbourg')
print(cities)
cities=set(['Frankfurt','Basel','Freiburg'])
cities=frozenset(['Frankfurt','Basel','Freiburg'])
#cities.add('Strasbourg')
print(cities)
adjectives={'cheap','expensive','inexpensive','economical'}
print(adjectives)
more_cities={'Delhi','Mumbai','Mandsour'}
cities_backup=more_cities.copy()
more_cities.clear()
print(cities_backup)
x={'a','b','c','d','e'}
y={'b','c'}
z={'c','d'}
print(x.difference(y))
print(x.difference(y).difference(z))
print(x-y)
print(x-y-z)
x={'a','b','c','d','e'}
y={'b','c'}
x.difference_update(y)
print(x)
x={'a','b','c','d','e'}
y={'b','c'}
x=x-y
print(x)
x={'a','b','c','d','e'}
x.discard('a')
print(x)
x.discard('z')
print(x)
x={'a','b','c','d','e'}
x.remove('a')
print(x)
x={'a','b','c','d','e'}
#x.remove('f')
x={'a','b','c','d','e'}
y={'c','d','e','f','g'}
print(x.intersection(y))
print(x&y)
z={'p','q'}
print(x.isdisjoint('z'))
print(x.isdisjoint('y'))
print(x.isdisjoint(y))
x={'a','b','c','d','e'}
y={'c','d'}
print(x.issubset(y))
print(y.issubset(x))
print(x<y)
print(y<x)
print(x<x)
print(x<=x)
x={'a','b','c','d','e'}
y={'c','d'}
print(x.issuperset(y))
print(x>y)
print(x>=y)
print(x>=x)
print(x>x)
print(x.issuperset(x))
x={'a','b','c','d','e'}
print(x.pop())
print(x.pop())
y={}
print(y.pop())
|
61d145c1068e99ea1efab8fc835b0216616ab33b | Android-Ale/PracticePython | /mundo3/INPUTNATUPLAVENDOPOSIÇÃO.py | 509 | 4.09375 | 4 | a = (int(input('Digite um número: ')),
int(input('Digite outro número:')),
int(input('DIgite mais um número: ')),
int(input('Digite o último número: ')))
print(f'Você digitou os valores {a}')
print(f'O valor 9 apareceu {a.count(9)} vezes.')
if 3 in a:
print(f'O valor 3 aparece na posição {a.index(3)+1}°')
else:
print('O valor 3 não foi digitado.')
print('Os valores pares digitados foram ', end='')
for número in a:
if número % 2 == 0:
print(número, end=',') |
7aa098ea67aa494cb4e4dfaa32b26edc84697683 | bidgars/python | /lambda.py | 680 | 3.59375 | 4 | # lambda arguments : expression
add10 = lambda x: x + 10
print(add10(1))
mult = lambda x, y: x * y
print(mult(2, 7))
points = [(1, 2), (15, 1), (5, -1), (10, 4)]
print(points)
print(sorted(points))
points_sorted = sorted(points, key=lambda x: x[1])
print(points_sorted)
points_sorted = sorted(points, key=lambda x: x[0] + x[1])
print(points_sorted)
# map(func,sq)
a = [1, 2, 3, 4, 5]
b = list(map(lambda x: x * 2, a))
print(b)
b = [x * 2 for x in a]
print(b)
# filter(func, seq)
b = list(filter(lambda x: x % 2 == 0, a))
print(b)
b = [x for x in a if x % 2 == 0]
print(b)
# reduce (func, seq)
from functools import reduce
prod = reduce(lambda x, y: x * y, a)
print(prod)
|
7ed5f7e1c22f59a946078ae7d3db7ab8def02f51 | professorbossini/20212_fatec_ipi_pbd_regressao_linear_simples | /regressao_linear_simples.py | 1,362 | 3.703125 | 4 | import numpy
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
dataset = pd.read_csv ('dados_regressao_linear_simples.csv')
x = dataset.iloc[:, :-1].values
# print (x)
y = dataset.iloc[:, -1].values
# print (y)
x_treinamento, x_teste, y_treinamento, y_teste = train_test_split(x, y, test_size=0.2, random_state=0)
linearRegression = LinearRegression()
linearRegression.fit(x_treinamento, y_treinamento)
y_pred = linearRegression.predict(x_treinamento)
# plt.scatter(x_treinamento, y_treinamento, color="red")
# plt.plot (x_treinamento, y_pred, color="blue")
# plt.title ("Salário x Tempo de Experiência (Treinamento")
# plt.xlabel ("Anos de Experiência")
# plt.ylabel ("Salário")
# plt.show()
# plt.scatter (x_teste, y_teste, color="red")
# plt.plot (x_treinamento, y_pred, color="blue")
# plt.title("Salário x Tempo de Experiência (Teste")
# plt.xlabel ("Anos de Experiência")
# plt.ylabel ("Salário")
# plt.show()
# print (f"15.7 anos: {linearRegression.predict([ [15.7] ])}")
# print (f"10.5 anos: {linearRegression.predict([ [10.5] ])}")
# print (f"0 anos: {linearRegression.predict([ [0] ])}")
# print (f"5 anos: {linearRegression.predict([ [5] ])}")
print(f'y={linearRegression.coef_[0]:.2f}x + {linearRegression.intercept_:.2f}')
|
79b8eaf4ac73a82430affc499b60adc5c7710e1d | divercraig/AdventOfCode2018 | /day1/puzzle1.py | 669 | 3.765625 | 4 | current_frequency = 0
frequency_history = {0}
found_reoccurance = False
while not found_reoccurance:
for line in open('input.txt'):
change = int(line)
new_frequency = current_frequency + change
print("Current Frequency is {}, change of {}, resulting frequency is {}"
.format(current_frequency, change, new_frequency)
)
current_frequency = new_frequency
if current_frequency in frequency_history:
print("The first re-occurence is {}".format(current_frequency))
found_reoccurance = True
break
else:
frequency_history.add(current_frequency)
|
e23c5d0da91649c8f70970fa1a9a4b5e41462ecd | slutske22/Practice_files | /python_for_js_devs/try-except.py | 165 | 3.5 | 4 | # %%
my_dict = {
"title": "Python is charming"
}
print(my_dict["title"])
try:
print(my_dict["author"])
except KeyError:
print("Anonymous Author")
# %%
|
73862a2dd84deb27a2ddfa2b726139c208feb05c | Tim-Barton/BudgetTracker | /src/ui/cli.py | 1,237 | 3.921875 | 4 |
def PrintCurrentCategories(categoryList):
i = 1
for category in categoryList:
print("{}\t{}".format(i, category))
i = i+1
def PromptForNewCategory(categoryManager):
categories = categoryManager.getCategoryNames()
print("Your currently configured Categories are:")
PrintCurrentCategories(categories)
return input("Please enter another desired Category:\n:")
def PromptSelectCategory(categoryManager):
categories = categoryManager.getCategoryNames()
print("Please select a category:")
PrintCurrentCategories(categories)
selection = input("Enter Number:")
selection = int(selection)
if selection <= len(categories):
return categories[selection-1]
return None
def PromptCategoryRegexRelation(categoryManager, regex):
print("Which Category does this regex belong to? {}".format(regex))
category = PromptSelectCategory(categoryManager)
if category is None:
categoryManager.addRegexToCategory("Unknown", regex)
else:
categoryManager.addRegexToCategory(category, regex)
def PrintError(error):
print(error)
def PrintFinalOutput(spendingMap):
for key, value in spendingMap.items():
print(key + " " + str(value))
|
745200fcaa22ab6771a20ace4343c80d8f1f2735 | mhall12/SOLSTISE_Simulation | /massreader.py | 7,199 | 3.796875 | 4 | import re
import numpy as np
def readmass(reac):
#reac = input("Enter a reaction of the form d(17F,p): ")
# reac = 'd(28Si,p)'
# firstpos grabs the position of the ( so we can get the target
firstpos = reac.find('(')
# target mass and symbol grabbed here
target = reac[:firstpos]
# splittarget initialized. It's used later to split the mass from the symbol
splittarget = []
# if statements on case the user typed p, d, etc.
# The else condition splits the mass from the symbol into an array
# with an empty element in the front (not sure why)
if target == 'p':
splittarget = ['', '1', 'H']
elif target == 'd':
splittarget = ['', '2', 'H']
elif target == 't':
splittarget = ['', '3', 'H']
elif target == 'a':
splittarget = ['', '4', 'He']
else:
splittarget = re.split('(\d+)',target)
# beam happens the same as the target:
secondpos = reac.find(',')
beam = reac[(firstpos+1):secondpos]
splitbeam = []
if beam == 'p':
splitbeam = ['', '1', 'H']
elif beam == 'd':
splitbeam = ['', '2', 'H']
elif beam == 't':
splitbeam = ['', '3', 'H']
elif beam == 'a':
splitbeam = ['', '4', 'He']
else:
splitbeam = re.split('(\d+)', beam)
# ejectile happens the same as the last two
thirdpos = reac.find(')')
ejectile = reac[(secondpos+1):thirdpos]
splitejectile = []
if ejectile == 'p':
splitejectile = ['', '1', 'H']
elif ejectile == 'd':
splitejectile = ['', '2', 'H']
elif ejectile == 't':
splitejectile = ['', '3', 'H']
elif ejectile == 'a':
splitejectile = ['', '4', 'He']
else:
splitejectile = re.split('(\d+)', ejectile)
# recoil is a bit different, since the user does not need to specify it. Instead, it has to
# be calculated from the inputs that were given.
# File name is specified here for the masses. It has the structure:
# Z A Symbol Mass_MeV Mass_u
infile = 'masses.txt'
# Generate a numpy array from the mass file. The dtype is needed because otherwise the symbols try to
# get read in as numbers and fill the arrays with NaN
data = np.genfromtxt(infile, delimiter='\t', dtype = 'unicode')
# Grab each column and put it into its own array to make it a little easier
z = data[:, 0]
a = data[:, 1]
symb = data[:, 2]
massMeV = data[:, 3]
massu = data[:, 4]
# These generate a mask for the target, beam, and ejectile that are True on the row where the
# specific isotope is located, and false on all the other lines. The masks will be used to grab
# the masses later. The string.lower() command takes the isotopic symbol and makes it lower case
# so it can be matched to the one in the file. So, we're matching the mass and the symbol.
if len(splittarget) != 3:
print("ERROR: The target you entered does not exist.")
tmassnum = str(input("Please enter the mass number (A): "))
telem = input("Please enter the elemental symbol: ")
splittarget = ['', tmassnum, telem]
if len(splitbeam) != 3:
print("ERROR: The beam you entered does not exist.")
bmassnum = str(input("Please enter the mass number (A): "))
belem = input("Please enter the elemental symbol: ")
splitbeam = ['', bmassnum, belem]
if len(splitejectile) != 3:
print("ERROR: The ejectile you entered does not exist.")
emassnum = str(input("Please enter the mass number (A): "))
eelem = input("Please enter the elemental symbol: ")
splitejectile = ['', emassnum, eelem]
masktarget = (splittarget[2].lower() == symb) & (a == splittarget[1])
maskbeam = (splitbeam[2].lower() == symb) & (a == splitbeam[1])
maskejectile = (splitejectile[2].lower() == symb) & (a == splitejectile[1])
# The Z for the target, beam, and ejectile are found here by masking the z array. It will now only have one
# element, which is an integer.
while len(z[masktarget]) == 0:
print("ERROR: The target you entered does not exist.")
tmassnum = str(input("Please enter the mass number (A): "))
telem = input("Please enter the elemental symbol: ")
splitbeam = ['', tmassnum, telem]
masktarget = (splittarget[2].lower() == symb) & (a == splittarget[1])
while len(z[maskbeam]) == 0:
print("ERROR: The beam you entered does not exist.")
bmassnum = str(input("Please enter the mass number (A): "))
belem = input("Please enter the elemental symbol: ")
splitbeam = ['', bmassnum, belem]
maskbeam = (splitbeam[2].lower() == symb) & (a == splitbeam[1])
while len(z[maskejectile]) == 0:
print("ERROR: The beam you entered does not exist.")
emassnum = str(input("Please enter the mass number (A): "))
eelem = input("Please enter the elemental symbol: ")
splitejectile = ['', emassnum, eelem]
maskejectile = (splitejectile[2].lower() == symb) & (a == splitejectile[1])
ztarget = int(z[masktarget])
zbeam = int(z[maskbeam])
zejectile = int(z[maskejectile])
aejectile = int(a[maskejectile])
atarget = int(a[masktarget])
abeam = int(a[maskbeam])
# The proton number of the recoil is found here.
zrecoil = ztarget + zbeam - zejectile
# The mass A of the recoil is found here.
arecoil = int(splittarget[1]) + int(splitbeam[1]) - int(splitejectile[1])
# A recoil mask is made using the Z and A this time instead of symbol and A.
maskrecoil = (zrecoil == z.astype(np.int)) & (arecoil == a.astype(np.int))
# Now, the masses can be returned for the four particles by applying the mask to the mass arrays. Easy peasy.
masses = [float(massu[masktarget][0]), float(massu[maskbeam][0]), float(massu[maskejectile][0]),
float(massu[maskrecoil][0])]
# Here, we will reconstruct the reaction so we can update it if necessary in Event Builder.
if splittarget == ['', '1', 'H']:
target = 'p'
elif splittarget == ['', '2', 'H']:
target = 'd'
elif splittarget == ['', '3', 'H']:
target = 't'
elif splittarget == ['', '4', 'He']:
target = 'a'
else:
target = splittarget[1] + splittarget[2]
if splitbeam == ['', '1', 'H']:
beam = 'p'
elif splitbeam == ['', '2', 'H']:
beam = 'd'
elif splitbeam == ['', '3', 'H']:
beam = 't'
elif splitbeam == ['', '4', 'He']:
beam = 'a'
else:
beam = splitbeam[1] + splitbeam[2]
if splitejectile == ['', '1', 'H']:
ejectile = 'p'
elif splitejectile == ['', '2', 'H']:
ejectile = 'd'
elif splitejectile == ['', '3', 'H']:
ejectile = 't'
elif splitejectile == ['', '4', 'He']:
ejectile = 'a'
else:
ejectile = splitejectile[1] + splitejectile[2]
reac = target + '(' + beam + ',' + ejectile + ')'
return masses, ztarget, atarget, zejectile, aejectile, zbeam, abeam, reac
if __name__ == "__main__":
reac = input("Enter a reaction of the form d(17F,p): ")
print(readmass(reac))
|
b1146a46ee78d6e521f28457012acc8c89633c4a | japnitahuja/FirstHackathonChatBot | /chatbot_respond.py | 4,761 | 3.5625 | 4 | import nltk, string, random
#initialise
user_respond="What a party pooper! There wasn't much at the party."
#noise reduction/expression removal like "lah" and punctuation removal
def preprocessing(input_text):
def _remove_noise(input_text):
lst_stop_words=open("stop_words_and_singlish.txt", "r")
stop_words=[]
for line in lst_stop_words:
stop_words.append(''.join(line.strip().split("\n")))
lst_stop_words.close()
translator_punc=str.maketrans('','', string.punctuation)
words=input_text.translate(translator_punc)
words = words.split()
noise_free_words = [word for word in words if word not in stop_words]
noise_free_text = " ".join(noise_free_words)
return noise_free_text
words=(_remove_noise(input_text))
#word standardisation:
phrases=open("singlish_phrases.txt", "r")
singlish_phrases=[]
for line in phrases:
singlish_phrases.append(line.strip("\n").split(","))
phrases.close()
dic_singlish={x[0]:x[1] for x in singlish_phrases}
def _lookup_words(input_text):
words = input_text.split()
new_words = []
for word in words:
if word.lower() in dic_singlish:
word = dic_singlish[word.lower()]
new_words.append(word)
new_text = " ".join(new_words)
return new_text
new_words=_lookup_words(words)
#lemmtising and stemming
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
lem = WordNetLemmatizer()
stem = PorterStemmer()
word_result=[]
for word in new_words:
temp=lem.lemmatize(word)
word_result.append(temp)
new_words= ''.join(word_result)
return new_words
def topic_modelling(input_text):
doc_complete = [input_text]
doc_clean = [doc.split() for doc in doc_complete]
from gensim import corpora
import gensim
# Creating the term dictionary of our corpus, where every unique term is assigned an index.
dictionary = corpora.Dictionary(doc_clean)
# Converting list of documents (corpus) into Document Term Matrix using dictionary prepared above.
doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]
# Creating the object for LDA model using gensim library
Lda = gensim.models.ldamodel.LdaModel
# Running and Training LDA model on the document term matrix
ldamodel = Lda(doc_term_matrix, num_topics=1, id2word = dictionary, passes=50)
# Results
print(ldamodel.print_topics(num_topics=1, num_words=3))
#greeting check?
def greeting_check(input_text):
input_text = preprocessing(input_text)
greeting=list(input_text.split())
for i in range(len(greeting)):
if greeting[i].lower() in ['hello', 'hi', 'hey', 'supp']:
return True
return False
def medical_check(input_text):
input_text = preprocessing(input_text)
input_text=list(input_text.split())
for i in range(len(input_text)):
if input_text[i].lower() in ['medical', 'records', 'record']:
return True
return False
def check_blood_sugar(input_text):
input_text=preprocessing(input_text)
values=[]
for i in range(len(input_text)):
try:
value=float(input_text[i]) #loses all precision?
values.append(value)
except:
pass
for j in range(len(values)):
value=values[j]
if value > 6.0 and value < 4.0:
return "You are at: MEDIUM risk. Consult a medical professional."
elif value>=11.0 or value<=2.8:
return "You are at: HIGH risk. Please seek medical attention."
return "You are at: NO risk. Keep it up!"
def farewell_check(input_text):
input_text=preprocessing(input_text)
goodbye_file=open("singlish_goodbyes.txt", "r")
goodbye=[]
for line in goodbye_file:
goodbye.append((''.join(line.strip('\n').split('\n'))))
goodbye_file.close()
input_text=list(input_text.split())
for i in range(len(input_text)):
if input_text[i].lower() in ['thank', 'thanks', 'thk']:
return random.choice(['Thank you ah!', 'Thanks ah!', 'No problem!'])
elif input_text[i].lower() in ['bye', 'exit', 'see you', 'later', 'goodbye']:
return random.choice(goodbye)
else:
return "I dunno what you're saying, try saying something again bah."
import datetime
if datetime.date.today().strftime('%A') == 'Friday':
from datetime import datetime
if datetime.now().strftime('%H:%M')=='14:44':
print('Time to take your medication sia!')
print(topic_modelling(preprocessing(user_respond)))
|
22dd2b9e9e8df7f55ff3d0a907ecf4d37803018d | iap015/introprogramacion | /clases/imccondicionales.py | 910 | 3.84375 | 4 | #-----constantes-----#
PREGUNTA_PESO = "cuanto pesas? : "
PREGUNTA_ESTATURA = "cuanto mides en metros? : "
MENSAJE_BIENVENIDA = "hola, como estas? vamos a calcular tu imc"
MENSAJE_DESPEDIDA = "tu imc es ..."
MENSAJE_BAJO_PESO = "estas muy delgado"
MENSAJE_PESO_ADECUADO = "estas en forma"
MENSAJE_SOBRE_PESO = "ten cuidado, estas en sobre peso"
MENSAJE_OBESO = "estas obeso, cuidado"
#-----entrada codigo-----#
print (MENSAJE_BIENVENIDA)
peso = float (input (PREGUNTA_PESO))
estatura = float (input (PREGUNTA_ESTATURA))
imc = peso/(estatura**2)
isBajoPeso = imc < 18.5
isAdecuado = imc >=18.5 and imc < 25
isSobrePeso = imc >= 25 and imc < 30
resultado = ""
if (isBajoPeso) :
resultado = MENSAJE_BAJO_PESO
elif (isAdecuado) :
resultado = MENSAJE_PESO_ADECUADO
elif (isSobrePeso) :
resultado = MENSAJE_SOBRE_PESO
else :
resultado = MENSAJE_OBESO
print (MENSAJE_DESPEDIDA)
print (resultado)
|
cda4cce604475d291ab2898b7087ed50a3af4d1f | smtamh/oop_python_ex | /student_result/2019/01_number_baseball/baseball [2-5 김A].py | 3,773 | 3.703125 | 4 | # 숫자야구
import random
def make_num():
answer = []
num = list(range(10)) # 0~9의 숫자를 리스트로 만든다
random.shuffle(num) # 리스트를 랜덤으로 섞는다
for i in range(3):
answer.append(num[i]) # answer 이라는 리스트에 랜덤으로 섞은 0~9를 세개만 넣는다.
return answer # 만든 answer 리스트를 리턴
def scanf():
print("입력해봐 : ", end='')
mine = input()
list = []
try:
for ch in mine:
list.append(int(ch))
if len(list) != 3: # 입력받은 값이 숫자 3자리가 아닐 때 다시 입력 받게함
print("다시 입력하시오!!")
return scanf()
# T. 예외처리를 할때에는 명확하게 어떠한 예외를 처리 할지 명기 해야 한다.
except: # 입력받은 값은 숫자가 아닐때 다시 입력받게 함
print("다시 입력하시오!!")
return scanf()
return list # 숫자 3개가 들어있는 리스트를 리턴
def check(my_list):
# T. python 에서 모든 문자가 대문자인 변수는 '상수' 로 인식한다.
S = 0
B = 0
O = 0
if my_list == answer: # 내가 입력한 리스트와 정답 리스트가 같을 시 1을 리턴하고 함수 종료
print("지렸어요. 정답입니다!! 기분 쨰지죠?")
return 1
for i in range(3): # 내가 입력한 리스트와 정답 리스트를 비교하며 채점
if my_list[i] is answer[i]:
S += 1
elif my_list[i] is answer[0]:
if i != 0:
B += 1
elif my_list[i] is answer[1]:
if i != 1:
B += 1
elif my_list[i] is answer[2]:
if i != 2:
B += 1
else:
O += 1
print("S %d" % S) # 채점 결과 출력
print("B %d" % B)
print("O %d" % O)
return 0 # 답이 아닐 시 0을 리턴하며 함수 종료
print("지금부터 숫자야구 게임을 시작합니다. 10번의 시도 안에,세자릿수의 숫자를 맞추어주세요!!")
print("규칙은 다음과 같습니다.")
print("서로 다른 세자리 수로 이루어진 세자리 자연수가 랜덤으로 설정된다.")
print("세자리 자연수를 띄어쓰기 없이 연속해서 입력하여 맞춘다..")
print("S : 숫자의 위치와 종류까지 맞춘 자릿수의 수.")
print("B : 숫자의 위치는 다르나, 종류를 맞춘 자릿수의 수.")
print("O : 숫자의 위치와 종류 모두 다른 자릿수의 수.")
print("이제 시작해주세요 ^0^")
print("=" * 50)
p = 1
return_o = 0
while p:
answer = make_num() # 정답 랜덤으로 생성
try_n = 1
while try_n <= 10: # 시도 횟수가 10번 이하일 때만 실행
my_list = scanf() # 도전자에게 입력 받음
correct = check(my_list) # 채점함수의 리턴값을 변수로 받음
if correct == 1: # 정답이 맞다면 while 문 종료
break
if try_n != 10: # 현재 시도 횟수 알려줌
print("현재 시도 횟수는 %d 회입니다 !! 화이팅" % try_n)
try_n += 1
if try_n > 10:
print("시도 가능한 기회를 모두 소진해버렸어요 ㅠㅠ 바보")
print("한 번 더 시도해 볼래? (y/n)")
# while 1:
while True:
return_o = input() # 다시 게임할지 안할지 입력받음
if return_o == 'n': # 안한다고 한다면 while문 종료 후 프로그램 종료
p = 0
break
if return_o == 'y': # 한다고 한다면 다시 실행
break
print('y 또는 n으로 대답하렴 ^^') # y 또는 n으로 대답하지 않았다면 다시 입력하게 함
|
b90889eb5de099bb1411e6a4bc6c76b9d699b92e | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/nvnjam003/boxes.py | 641 | 4 | 4 | def print_square():
for x in range (0, 5):
if (x == 0 or x == 4):
print (5*"*")
else:
print ("*" + 3*" " + "*")
def print_rectangle(width, height):
for x in range(0, height):
if (x == 0 or x == (height-1)):
print (width*"*")
else:
print ("*" + (width-2)*" " + "*")
def get_rectangle(width, height):
rectangle = ""
for x in range(0, height):
if (x == 0 or x == (height-1)):
rectangle += width*"*" + "\n"
else:
rectangle += "*" + (width-2)*" " + "*\n"
return rectangle |
a5e68b71d66be36bbdd6e829c1b3f5b5451da76e | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/plsnor001/question3.py | 847 | 3.796875 | 4 | def intake():
first_name=input('Enter first name: \n')
last_name=input('Enter last name: \n')
money=eval(input('Enter sum of money in USD: \n'))
country=input('Enter country name: \n')
k=0.3*money
def output():
print("\nDearest {0}\nIt is with a heavy heart that I inform you of the death of my father,\nGeneral Fayk {1}, your long lost relative from Mapsfostol.\nMy father left the sum of {2}USD for us, your distant cousins.\nUnfortunately, we cannot access the money as it is in a bank in {3}.\nI desperately need your assistance to access this money.\nI will even pay you generously, 30% of the amount - {4}USD,\nfor your help. Please get in touch with me at this email address asap.\nYours sincerely\nFrank {1}".format(first_name,last_name,money,country,k))
output()
intake()
|
542fce2c695b7656cfa173bd9ba011bf6a57146e | zxbange/OldBoy | /class9/生产者消费者模型.py | 603 | 3.546875 | 4 | import threading,time
import queue
q = queue.Queue(maxsize=10)
def Producer(name):
count = 1
while True:
q.put("骨头%s" % count)
print("生产了骨头%s\n" % count)
count += 1
time.sleep(1)
def Consumer(name):
while True:
# while q.qsize() > 0:
print("[%s] 取到 [%s], 并且吃了它\n" %(name, q.get()))
time.sleep(1)
p = threading.Thread(target=Producer, args=("Abbott",))
c = threading.Thread(target=Consumer, args=("ChengRonghua",))
c1 = threading.Thread(target=Consumer, args=("wangsen",))
p.start()
c.start()
c1.start() |
1cd4dcc06656eb21bfb550411732aa5710d3cd61 | flypigfish/test | /Test/hello.py | 1,768 | 3.65625 | 4 |
def matrix_multi():
a_row=2
a_col=3
b_row=3
b_col=4
a=[[1 for row in range(a_col)] for rows in range(a_row)]
b=[[2 for row in range(b_col)] for rows in range(b_row)]
a[0][0]=0
b[0][1]=1
for i in range(a_row):
for j in range(a_col):
print "%d %d val: %d" % (i,j,a[i][j])
# 2x3, 3x2 =2 x2
c_row=a_row
c_col=b_col
fixed=a_col
c=[[0 for row in range(c_col)] for rows in range(c_row)]
for i in range(c_row):
for j in range(c_col):
for r in range(fixed):
c[i][j] += (a[i][r]*b[r][j])
for row in c:
print row
def fff():
a=[1,2,3]
b=[1,3,5]
c=set()
for i in range(len(a)):
x=a[i]
for j in range(len(b)):
y=b[j]
if x!=y:
tmp=list()
tmp.append(x)
tmp.append(y)
t=frozenset(tmp)
c.add(t)
print(c)
def ggg():
a=[{1,3},{1,5}]
b=[{2,3},{2,5}]
c=list()
for i in range(len(a)):
x=a[i]
for j in range(len(b)):
y=b[j]
if x!=y:
tmp=set()
tmp=tmp.union(x)
tmp=tmp.union(y)
c.append(tmp)
print(c)
if __name__=="__main__":
num=5
matrix_multi()
# b=[[0 for i in range(5)] for j in range(5)]
# for row in b:
# print row
# c=[2,3,4,5,6,7]
# for i in range(len(c)):
# print "%d %d" % (i, c[i])
# print 1/2.0
# print "Hello, Python!" |
a2e61e668a4e487a13480eda6c8f914e2f539a1e | markwatkinson/project-euler | /9.py | 503 | 3.796875 | 4 | """
1) a < b < c
2) a*a + b*b = c*c
3) a + b + c = 1000
find a*b*c
"""
"""
2 => sqrt(a*a + b*b) = c
sub into 3)
a + b + sqrt(a*a + b*b) = 1000
now we have only two unknowns
"""
import math
a, b = None, None
for b in range(1000, 0 ,-1):
brk = False
for a in range(b-1, 0, -1):
if a + b + math.sqrt(a*a + b*b) == 1000:
brk = True
break
if brk:
break
c = int(math.sqrt(a*a + b*b))
assert(a + b + c) == 1000
print 'a, b, c =', a, b, c
print 'abc = ' + str(a*b*c)
|
aa670dcef38164ef87d888a531cf196d1746f14d | roni-kemp/python_programming_curricula | /CS1/0350_list_projects/magic_8_ball_answer.py | 455 | 3.828125 | 4 | import random
#http://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python/
options = ["It is certain","Outlook good","You may rely on it","Ask again later","Concentrate and ask again","Reply hazy, try again","My reply is no","My sources say no"]
question = True
while question:
question = input("Ask the magic 8 ball a question: (press enter to quit) ")
answers = random.randint(0,7)
print(options[answers])
|
0c8e476246f473c463914242b1960e8d5679b2ba | Vatican-Cameos/Algorithms | /Min Cost Climbing Stairs.py | 739 | 3.6875 | 4 | # On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
# Once you pay the cost, you can either climb one or two steps.
# You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0,
# or the step with index 1.
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
# DP - Recurrence Relation : opt[i] = min(opt[i-1] + cost[i-1], opt[i-2] + cost[i-2])
size = len(cost)
opt = [None] * (size + 1)
opt[0] = 0
opt[1] = 0
for i in range(2, size + 1):
print(i)
opt[i] = min(opt[i-1] + cost[i-1], opt[i-2] + cost[i-2])
return opt[size]
|
225f6b81a6cc1e701452a9584808037a88530fb5 | emilydlu/exercism-python | /hamming/hamming.py | 140 | 3.5625 | 4 |
def distance(a, b):
if len(a)!= len(b):
return
counter = 0
for i in range(len(a)):
if a[i]!= b[i]:
counter+=1
return counter
|
3b12ec57154e8f766b4d2fe790a3ef9e959e01c0 | wilbertgeng/LintCode_exercise | /DFS/10.py | 1,359 | 3.96875 | 4 | """10. String Permutation II"""
class Solution:
"""
@param str: A string
@return: all permutations
"""
def stringPermutation2(self, str):
# write your code here
if not str:
return [""]
res = []
str = list(str)
str.sort()
self.dfs(str, [], res)
return res
def dfs(self, s, path, res):
if not s:
path = "".join(path)
res.append(path)
return
for i in range(len(s)):
if i > 0 and s[i] == s[i - 1]:
continue
path.append(s[i])
self.dfs(s[:i] + s[i + 1:], path, res)
path.pop()
####
str = list(str)
str.sort()
.
visited = [False] * len(str)
res = []
self.dfs(str, [], visited, res)
return res
def dfs(self, string, path, visited, res):
if len(path) == len(string):
res.append("".join(path))
return
for i in range(len(string)):
if visited[i]:
continue
if i > 0 and string[i] == string[i - 1] and not visited[i - 1]:
continue
visited[i] = True
path += string[i]
self.dfs(string, path, visited, res)
path.pop()
visited[i] = False
|
9e45b98de15fcd26affba22a2c22e5946737a6d9 | jorge-alvarado-revata/code_educa | /python/week8/r_ejem04.py | 158 | 3.625 | 4 |
# inverso de una cadena
def inverso(s):
if s == '':
return ''
else:
return inverso(s[1:]) + s[0]
print(inverso('hola como estas'))
|
3f6cfb6d2b15a69ce0c80440093376b2e6e2b3d0 | yeduxiling/pythonmaster | /absex84.py | 224 | 3.828125 | 4 | n = int(input('请输入一个数:'))
def is_positive(n):
if n > 0:
return True
else:
return False
if is_positive(n):
print(f"{n}是个正数")
else:
print(f"{n}不是正数")
|
93909bccd922814dfe22c9e6758a7aadb8085f80 | phamvantai/bai6 | /t6.2.py | 273 | 3.578125 | 4 | class Hinhchunhat(object):
def __init__(self, a):
self.canh = a
def __init__(self,b):
self.canh = b
##################################
def area(self):
return.self.canh*a*b
aHinhchunhat = Hinhchunhat(2)
print(aHinhchunhat.area()) |
cd9482433dcab725c4935eb457b87fab0fc9a2c2 | justagist/tf_playground | /autoencoder_mnist.py | 9,516 | 3.578125 | 4 | '''
# autoencoder class to learn and predict mnist images: Reduces 28x28 image to a 2D value and learns to predict the class from it.
@author: JustaGist
@package: tf_playground
'''
import sys
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import matplotlib.pyplot as plt
def load_mnist_data():
return input_data.read_data_sets("MNIST_data/", one_hot=True)
class AutoEncoder:
def __init__(self):
self._data = mnist
self._define_model()
self._sess = tf.Session()
# self._saver = tf.train.Saver()
self._use_saved_model = False
# self.plot_training_losses()
def _define_model(self):
self._input = tf.placeholder(tf.float32, [None, 784])
self._create_encoder_network()
self._create_decoder_network()
self._define_loss_functions()
def _define_loss_functions(self):
self._true_output = tf.placeholder(tf.float32, [None, 784]) # actual answer
self._pv = tf.placeholder(tf.float32, [1, 2]) # Sparsity prob
self._beta = tf.placeholder(tf.float32, [1, 1]) # Sparsity penalty (lagrange multiplier)
# Aditional loss for penalising high activations (http://ufldl.stanford.edu/tutorial/unsupervised/Autoencoders/)
# p = tf.nn.softmax(encoder_op)
# kl_divergence = tf.reduce_mean(tf.mul(self._pv,tf.log(tf.div(self._pv,p))))
# sparsity_loss = tf.mul(self._beta,kl_divergence)
# add_n gives the sum of tensors
weight_decay_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])
squared_loss = tf.reduce_sum(tf.square(self._train_decode - self._true_output))
self._loss_op = tf.reduce_mean(squared_loss) + 0.1*weight_decay_loss #+ sparsity_loss
self._train_op = tf.train.AdadeltaOptimizer(learning_rate=0.1, rho=0.1, epsilon=0.0001).minimize(self._loss_op)
def train_network(self, save_values = True, show_train = False, epochs = 10000):
if save_values:
saver = tf.train.Saver()
self._init_op = tf.global_variables_initializer()
self._sess.run(self._init_op)
loss = [0]*epochs
# with tf.device(device_string):
i = 0
training_done = False
while not training_done:
try:
batch_xs, _ = mnist.train.next_batch(100)
#_, self._loss[i] = sess.run([train_op, self._loss_op], feed_dict={x: batch_xs, self._true_output: batch_xs})
_, loss[i] = self._sess.run([self._train_op, self._loss_op], feed_dict={self._input: batch_xs, self._true_output: batch_xs, self._pv: [[0.02,0.98]], self._beta: [[0.1]]})
i+=1
if (i+1)%(int(epochs/10))==0:
print "Training: {0:.0f}%".format((i+1)/float(epochs)*100)
if show_train:
idx = 3
out_code, out_decode = self._sess.run([self._encoder_op,self._train_decode], feed_dict={self._input: np.expand_dims(mnist.test.images[idx,:],0)})
plt.subplot(1,4,1)
plt.imshow(np.reshape(mnist.test.images[idx,:],(28,28)))
plt.subplot(1,4,2)
plt.imshow(np.reshape(out_decode,(28,28)))
idx = 5
out_code, out_decode = self._sess.run([self._encoder_op,self._train_decode], feed_dict={self._input: np.expand_dims(mnist.test.images[idx,:],0)})
plt.subplot(1,4,3)
plt.imshow(np.reshape(mnist.test.images[idx,:],(28,28)))
plt.subplot(1,4,4)
plt.imshow(np.reshape(out_decode,(28,28)))
plt.show()
if i >= epochs:
training_done = True
except KeyboardInterrupt:
break
if save_values:
save_path = saver.save(self._sess, save_file)
print("Model saved in path: %s" % save_path)
self._loss = loss
def plot_training_losses(self, loss = None):
if loss is None:
loss = self._loss
print "plotting_losses"
plt.plot(np.r_[loss].ravel())
plt.show()
def decode(self, code_in, plot=True):
out_decode = self._sess.run([self._decoder], feed_dict={self._code_in: code_in[0]})[0]
if plot:
# plt.subplot(1,2,1)
plt.imshow(np.reshape(out_decode,(28,28)))
plt.show()
return out_decode
def encode_mnist_image(self, image_idx):
code = self.encode_image(mnist.test.images[image_idx,:])
return code
def encode_image(self, image):
code = self._sess.run([self._encoder_op], feed_dict={self._input: np.expand_dims(image,0)})
return code
def encode_decode_mnist(self, image_idx):
out_code, out_decode = self._sess.run([self._encoder_op, self._train_decode], feed_dict={self._input: np.expand_dims(mnist.test.images[image_idx,:],0)})
return out_code, out_decode
def decode_and_compare(self, code, mnist_image_idx):
plt.subplot(1,2,1)
plt.imshow(np.reshape(mnist.test.images[mnist_image_idx,:],(28,28)))
out_decode = self.decode(code, plot=False)
plt.subplot(1,2,2)
plt.imshow(np.reshape(out_decode,(28,28)))
plt.show()
def test_autoencoding(self, image_idx):
self.decode_and_compare(self.encode_mnist_image(image_idx),image_idx)
def _create_encoder_network(self):
# Create an encoder network. Encoder layer: i/p = 784D; o/p = 50D.
# Bottleneck layer: i/p = 50D; o/p == 2D.
# Gives out a 'code' of the input (image)
with tf.variable_scope('encoder'):
## Encoder weights and bias
W_fc1 = tf.Variable(tf.random_uniform([784,50], dtype=tf.float32))
b_fc1 = tf.Variable(tf.random_uniform([50], dtype=tf.float32))
## Bottleneck weights and bias
W_fc2 = tf.Variable(tf.random_uniform([50,2], dtype=tf.float32))
b_fc2 = tf.Variable(tf.random_uniform([2], dtype=tf.float32))
# connecting the layers
h1_enc = tf.nn.tanh(tf.matmul(self._input, W_fc1) + b_fc1)
self._encoder_op = tf.nn.tanh(tf.matmul(h1_enc, W_fc2) + b_fc2)
def _create_decoder_network(self):
# Create decoder network to decode the code and output the actual image
with tf.variable_scope('decoder'):
self._code_in = tf.placeholder(tf.float32,[None,2])
W_fc1 = tf.Variable(tf.random_uniform([2,50], dtype=tf.float32))
b_fc1 = tf.Variable(tf.random_uniform([50], dtype=tf.float32))
W_fc2 = tf.Variable(tf.random_uniform([50,784], dtype=tf.float32))
b_fc2 = tf.Variable(tf.random_uniform([784], dtype=tf.float32))
h1_dec = tf.nn.tanh(tf.matmul(self._encoder_op, W_fc1) + b_fc1)
self._train_decode = tf.nn.tanh(tf.matmul(h1_dec, W_fc2) + b_fc2) # output decoder while training
h1_dec = tf.nn.tanh(tf.matmul(self._code_in, W_fc1) + b_fc1)
self._decoder = tf.nn.tanh(tf.matmul(h1_dec, W_fc2) + b_fc2) # output decoder for testing (requires _code_in placeholder)
def load_saved_model(self):
saver = tf.train.Saver()
saver.restore(self._sess, load_file)
print "Restored Session Model from", load_file
self._use_saved_model = True
if __name__ == '__main__':
save_file = "_training_saves/autoencoder_test_mnist.ckpt"
load_file = "_training_saves/autoencoder_default_mnist.ckpt"
if len(sys.argv) < 2:
print "USAGE: python autoencoder_mnist.py train [num_epochs] [save?] [save_path]\n\t or: python autoencoder_mnist.py test [MNIST test datatset img index]"
else:
mnist = load_mnist_data()
aen = AutoEncoder()
if sys.argv[1] == 'train':
epochs = 1000
save = False
if len(sys.argv) > 2:
epochs = int(sys.argv[2]) if (sys.argv[2] != '0') else epochs
if len(sys.argv) > 3:
save = bool(int(sys.argv[3]))
if len(sys.argv) > 4 and save == True:
save_file = sys.argv[4]
save_file = '_training_saves/'+ save_file if '_training_saves/' not in save_file else save_file
save_file = save_file + '.ckpt' if '.ckpt' not in save_file else save_file
print "Starting Training with {0:.0f} epochs".format(epochs)
aen.train_network(epochs=epochs, save_values = save)
elif sys.argv[1] == 'test':
idx = 100
if len(sys.argv) > 2:
idx = int(sys.argv[2])
if len(sys.argv) > 3:
load_file = sys.argv[3]
load_file = '_training_saves/'+load_file if '_training_saves/' not in load_file else load_file
load_file = load_file + '.ckpt' if load_file[:-5] != '.ckpt' else load_file
aen.load_saved_model()
aen.test_autoencoding(idx)
else:
print "Invalid Usage."
print "USAGE: python autoencoder_mnist.py train [num_epochs] [save?] [save_path]\n\t or: python autoencoder_mnist.py test [MNIST test datatset img index]" |
421051e22264c10822544e58835b1c8349f71a7f | KATO-Hiro/AtCoder | /Others/paken/pakencamp-2018-day3/a.py | 216 | 3.546875 | 4 | # -*- coding: utf-8 -*-
def main():
y, m, d = map(int, input().split())
if m == 12 and d == 25:
print(y - 2018)
else:
print('NOT CHRISTMAS DAY')
if __name__ == '__main__':
main()
|
97a472785b7024fb576dfd8cb00e637d2e8b2b73 | domantasjurkus/python | /euler/16_euler.py | 102 | 3.6875 | 4 | num = 2**1000
sum = 0
num = str(num)
for char in num:
sum += int(char)
print "Final sum:", sum
|
7a93dcb7fb2be4fc2f16cbe196583b8a55a96978 | larlyssa/uoft_csc108H | /tic-tac-toe/tictactoe_functions.py | 2,848 | 4.34375 | 4 | import math
EMPTY = '-'
def is_between(value, min_value, max_value):
""" (number, number, number) -> bool
Precondition: min_value <= max_value
Return True if and only if value is between min_value and max_value,
or equal to one or both of them.
>>> is_between(1.0, 0.0, 2)
True
>>> is_between(0, 1, 2)
False
"""
if value >= min_value and value <= max_value:
return True
else:
return False
def game_board_full(game_board):
"""
Returns true if the board game is full. Otherwise, returns false.
"""
for space in game_board:
if space == EMPTY:
return False
return True
def get_board_size(game_board):
"""
Checks that the game board is a perfect square, then returns the length of the columns/rows.
"""
board_str_len = len(game_board)
if board_str_len ** 0.5 == round(board_str_len ** 0.5):
return int(board_str_len ** 0.5)
else:
return "Error: board not a perfect square."
def make_empty_board(length):
"""
Creates an empty board of the desired length, filled only with empty '-' characters.
"""
empty_board = ""
for instance in range(length):
empty_board += EMPTY
return empty_board
def get_position(row, column, board_size):
"""
Returns the position in a string for a (row, column) coordinate, given the board size.
"""
str_index = (row - 1) * board_size + column - 1
return str_index
def make_move(symbol, row, column, game_board):
"""
Makes a move, adding the symbol to the appropriate (row, column) on the game board. Precondition that the move is made in an empty square.
"""
move_pos = get_position(row, column, get_board_size(game_board))
new_board = game_board[:int(move_pos)] + symbol + game_board[int(move_pos + 1):]
return new_board
def extract_line (game_board, direction, direction_location):
"""
Returns the characters that makes up the specified row.
"""
board_size = get_board_size(game_board)
line = ""
if direction == 'down':
for symbol in range(1, int(board_size) + 1):
symbol_pos = get_position(symbol, direction_location, board_size)
line += game_board[symbol_pos]
elif direction == 'across':
for symbol in range(1, int(board_size) + 1):
symbol_pos = get_position(direction_location, symbol, board_size)
line += game_board[symbol_pos]
elif direction == 'down_diagonal':
for symbol in range(1, int(board_size) + 1):
symbol_pos = get_position(symbol, symbol, board_size)
line += game_board[symbol_pos]
elif direction == 'up_diagonal':
for symbol in range(1, int(board_size) + 1):
symbol_pos = get_position(board_size - symbol + 1, symbol, board_size)
line += game_board[symbol_pos]
return line
|
33a26f0aaca6c8f32e2e6657c9c1f11a048a77c2 | sandip-gavade/python_practice | /conditional.py | 487 | 4.03125 | 4 | n = int(input("please input a number "));
if n<=100 and n>=1:
print("you have entered -",n," this is between 1 and 100");
if n<=50 and n>=1:
print("you have entered -", n, " this is between 1 and 50");
if n<=25 and n>=1:
print("you have entered -", n, " this is between 1 and 25");
elif n<=200 and n>=101:
print("you have entered -", n, " this is between 101 and 200");
else:
print("you have entered -", n, " this is not between 1 and 200"); |
f7924e7a60a844350e865c72e6aee17501e75374 | p4panash/Algorithms-and-Programming | /Lab3/ReadFile.py | 1,341 | 4.4375 | 4 | def ReadFromFile(currentArray, fileName):
"""
Function used in order to change the current list with a list from a file
Input: currentArray - an array of integers representing the current array
Output: an array with elements from file
"""
array = []
try:
file = open(fileName, "r")
numberOfElements = int(file.readline())
arrayOfElements = [element for element in file.read().split(", ")]
for index in range(numberOfElements + 1):
if index > len(arrayOfElements) - 1:
break
try:
element = int(arrayOfElements[index])
array.append(element)
except ValueError:
pass
except ValueError:
print(" Invalid input ! Please check the input file !")
except IOError:
print(" File can not be found !")
return currentArray
return array
def WriteInFile(currentArray, fileName):
"""
Function used in order to write the content of the current list in a file
Input: currentArray - an array of integers representing the current array
"""
try:
file = open(fileName, "w")
text = ""
for element in currentArray:
text += str(element) + ", "
file.write(text)
except IOError:
print("IO Error") |
b6d81ca1976b446d4ce385728828c80663db53f5 | eidleweise/ToolsForWishblendRPG | /PhonePad.py | 2,238 | 3.9375 | 4 | # Import the groupby function from itertools,
# this takes any sequence and returns an array of groups by some key
from itertools import groupby
# Use a dictionary as a lookup table
dailpad = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z'],
'0': [' '],
}
def phone_pad(input_str):
# Convert to string if given a number
if (input_str.isnumeric()):
if type(input_str) == int:
input_str = str(input_str)
# Create our string output for the dialed numbers
output = ''
# Group each set of numbers in the order
# they appear and iterate over the groups.
# (eg. 222556 will result in [(2, [2, 2, 2]), (5, [5, 5]), (6, [6])])
# We can use the second element of each tuple to find
# our index into the dictionary at the given number!
for number, letters in groupby(input_str):
# Convert the groupby group generator into a list and
# get the offset into our array at the specified key
offset = len(list(letters)) - 1
# Check if the number is a valid dialpad key (eg. 1 for example isn't)
if number in dailpad.keys():
# Add the character to our output string and wrap
# if the number is greater than the length of the character list
output += dailpad[number][offset % len(dailpad[number])]
else:
raise ValueError(f'Unrecognized input "{number}"')
return output
else:
print("input was text " + input_str)
output = ''
for letter in input_str:
for key, value in dailpad.items():
#print(key, value)
if letter in value:
index = 0
for l in value:
index = index + 1
output = output + key
if letter == l:
break
return output
print('Write Text: ')
input_text = input().lower()
pad = phone_pad(input_text)
print(pad)
|
1d9b59a4604be6a8ccb5b4d95cdf79b051ced971 | DhanashreeRevagade/Clustering-Air-Objects_Challengers-of-the-Unknown | /calculate_angle_of_elevation.py | 1,854 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
v = 700
g=9.8
def get_data(path):
dataframe = pd.read_csv(path,usecols=['Longitude', 'Latitude','Altitude (m masl GPS)'],nrows=10)
return dataframe
def check_std(df):
'''
df: Dataframe Object
We will keep either Latitude/Longitude constant for initial position depending upon standard deviation
'''
std_lat = np.std(df.Latitude)
std_long = np.std(df.Longitude)
if std_lat>std_long:
return({'cord_used':'Latitude','cord_notused':'Longitude'})
else:
return({'cord_notused':'Latitude','cord_used':'Longitude'})
def find_trajectory(df,initial_time,time_step):
"""
df: Dataframe Object containing Predicted Longitude,Latitude , Altitude
initial_time: Time to reach first predicted point
time_step: Time Step for predicted data
This function is to find elevation angle and coordinates for finding missile launch
"""
lst=[]
t = initial_time
coordinate = check_std(df)
for i in range(0,len(df.values)):
inverse_value = ((df['Altitude (m masl GPS)'].values[i]) + ((0.5*g)*(t**2)))/(v*t) #Find angle at which we should hit
if inverse_value<1 and inverse_value>-1:
angle = math.asin(inverse_value)
x_coordinate = ((v*t)*math.cos(angle))
x_initial = df[coordinate['cord_used']].values[i] - ((x_coordinate)*math.pi)/180
temp_dict = {coordinate['cord_used']:x_initial,coordinate['cord_notused']:df[coordinate['cord_notused']].values[i],'time_of_impact':t,'angle_of_elev':math.degrees(angle)}
lst.append(temp_dict)
t+=time_step
return(lst)
df= get_data('C:/Users/Vivek_Chole/Desktop/SIH/data/newalldata.csv')
missile_data = find_trajectory(df,10,10)
print(missile_data)
|
d9b3edf3dc3ce5a69530e326144e025750ca3606 | jgrynczewski/zdpytpol16_design_patterns | /oop/duck_typing.py | 581 | 4.03125 | 4 | # If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck.
import abc
class SwimDuckAnimal(abc.ABC):
@abc.abstractmethod
def swim_quack(self):
pass
class Duck(SwimDuckAnimal):
def swim_quack(self):
print("Jestem kaczką")
class Dog(SwimDuckAnimal):
def swim_quack(self):
print("Jestem psem")
class Fish(SwimDuckAnimal):
def swim(self):
print("Jestem rybą")
def duck_testing(animal: SwimDuckAnimal):
animal.swim_quack()
duck_testing(Duck())
duck_testing(Dog())
duck_testing(Fish()) |
0feccb7a6f09a960a364ea46cd7929b18fe57258 | richardvecsey/python-basics | /060-break_continue.py | 655 | 4.25 | 4 | """
How to speed up for cycle with break and continue
-------------------------------------------------
continue: Jump to the next iteration, the remain part of the actual iteration
won't be executed
break: Jump out from the for loop, the remain part of the whole for cycle
won't be executed
"""
print('This is a normal for loop')
for i in range(4):
print(i)
print('\nThis is an example for continue')
for i in range(4):
if i == 2:
continue
print(i)
print('\nThis is an example for break')
for i in range(4):
if i == 2:
break
print(i)
print('\nEnd of examples') |
a09f428f0e0e1f79b64dd02f841da9656e335ea5 | abbasjam/abbas_repo | /python/func.py | 131 | 3.984375 | 4 |
x={'Name':"Abbas",'RN':"1188",'Age':"39",'Mark1':"90",'Mark2':"95"}
x["Mark3"]="67"
x.pop("Name")
y=x.copy()
print(y)
print(x)
|
b573017ca336216332be4612d48206ba1eaa6b8c | SyureNyanko/asymmetric_tsp | /asymmetric_tsp/core.py | 1,957 | 3.765625 | 4 | # -*- coding: utf-8 -*-
import math
import time
import sys
class Timeout(object):
def __init__(self, limittime, starttime):
self.starttime = starttime
self.limittime = limittime
def get_timeout(self, time):
timeout = (time - self.starttime> self.limittime)
return timeout
def testlength(v1, v2):
'''Measure length or cost'''
#t = (x1 - x2) * 100
#return t
#print(str(v1) + " , " + str(v2))
dv = (v1[0] - v2[0], v1[1] - v2[1])
d2 = dv[0] * dv[0] + dv[1] * dv[1]
d = math.sqrt(d2)
return d
def route_swap(s, a, b):
'''Generate new route s is old route, a and b are indexes'''
new_route = s[0:a+1]
mid = s[a+1:b+1]
new_route = new_route + mid[::-1]
new_route = new_route + s[b+1:]
return new_route
def calc_route_length(route, f):
ret = 0
for i in range(len(route)):
ret += f(route[i], route[(i+1)%len(route)])
return ret
def two_opt(route, length_function, limittime=60):
'''Peforms 2-opt search to improve route'''
timeout = Timeout(limittime, time.time())
bestroute = route
l = len(bestroute)
bestroute_cost = calc_route_length(bestroute, length_function)
while(True):
flag = True
if timeout.get_timeout(time.time()):
raise TimeoutError
for i in range(l-2):
i_next = (i + 1)%l
for j in range(i + 2, l):
j_next = (j + 1)%l
if i == 0 and j_next == 0:
continue
swapped_route = route_swap(bestroute, i, j)
swapped_route_cost = calc_route_length(swapped_route, length_function)
if swapped_route_cost < bestroute_cost:
print(str(i) + "," + str(j) + "," + str(bestroute))
bestroute_cost = swapped_route_cost
bestroute = swapped_route
flag = False
if flag:
break
return bestroute
if __name__ == '__main__':
'''point_tables is example case'''
point_table = [[0,0],[1,2],[10,0],[4,5],[2,0]]
point_size = len(point_table)
print("initial :" + str(point_table))
bestroute = two_opt(point_table, testlength)
print("result :" + str(bestroute))
|
08e6a33334f8e0ff8e896dece715c5dbd7d90b5c | zohaibafridi/Scripts_of_Data_Exploration_and_Analysis_Book | /Volume_II/3-Pandas/Code_Scripts/3.12-Aggregation.py | 2,342 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Applying Aggregations on DataFrame
#
# In[1]:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
index = pd.date_range('1/1/2000', periods=10),
columns = ['A', 'B', 'C', 'D'])
print (df)
r = df.rolling(window=3,min_periods=1)
print (r)
# ### Apply Aggregation on a Whole Dataframe
#
# In[2]:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
index = pd.date_range('1/1/2000', periods=10),
columns = ['A', 'B', 'C', 'D'])
print (df)
r = df.rolling(window=3,min_periods=1)
print (r.aggregate(np.sum))
# ### Apply Aggregation on a Single Column of a Dataframe
#
# In[4]:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
index = pd.date_range('1/1/2000', periods=10),
columns = ['A', 'B', 'C', 'D'])
print (df)
r = df.rolling(window=3,min_periods=1)
print (r['A'].aggregate(np.sum))
# ### Apply Aggregation on Multiple Columns of a DataFrame
# In[5]:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
index = pd.date_range('1/1/2000', periods=10),
columns = ['A', 'B', 'C', 'D'])
print (df)
r = df.rolling(window=3,min_periods=1)
print (r[['A','B']].aggregate(np.sum))
# ### Apply Multiple Functions on a Single Column of a DataFrame
#
# In[6]:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
index = pd.date_range('1/1/2000', periods=10),
columns = ['A', 'B', 'C', 'D'])
print (df)
r = df.rolling(window=3,min_periods=1)
print (r['A'].aggregate([np.sum,np.mean]))
# ### Apply Multiple Functions on Multiple Columns of a DataFrame
#
# In[7]:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4),
index = pd.date_range('1/1/2000', periods=10),
columns = ['A', 'B', 'C', 'D'])
print (df)
r = df.rolling(window=3,min_periods=1)
print (r[['A','B']].aggregate([np.sum,np.mean]))
# ### Apply Different Functions to Different Columns of a Dataframe
#
# In[8]:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 4),
index = pd.date_range('1/1/2000', periods=3),
columns = ['A', 'B', 'C', 'D'])
print (df)
r = df.rolling(window=3,min_periods=1)
print (r.aggregate({'A' : np.sum,'B' : np.mean}))
# In[ ]:
|
6315dd6a066de16269a84b22bc03cad2acaf1e88 | moongchi98/MLP | /백준/MAR-APR/12904_A와B.py | 331 | 3.59375 | 4 | S = input()
T = input()
while len(S) != len(T):
if T[-1] == 'A':
T = T[:-1]
else:
T = T[:-1]
T = T[::-1]
if len(S) > len(T):
result = 0
break
elif len(S) == len(T) and S != T:
result = 0
break
elif S == T:
result = 1
break
print(result)
|
39f22c6409e76b010a99d74a79f3e968ddb87fa8 | afieqhamieza/DataStructures | /python/split_string.py | 1,069 | 4.0625 | 4 | # Given a string s with length n, how many ways can you split it into two substrings s_1 and s_2
# such that the number of unique characters in s_1 and s_2 are the same?
# Parameter
# s: A string with length n.
# Result
# The number of ways you can split it into two substrings that satisfy the condition.
import collections
def total_ways_to_split_strings(s: str) -> int:
# WRITE YOUR BRILLIANT CODE HERE
left_count = collections.Counter()
right_count = collections.Counter(s)
res = 0
for c in s:
left_count[c] += 1
right_count[c] -= 1
if right_count[c] == 0:
del right_count[c]
if len(left_count) == len(right_count):
res += 1
return res
if __name__ == '__main__':
# "aaa" = 2
# "bac" = 0
# "sampletext" = 1
# "uwuwuwu" = 4
# "goooooooogle" = 1
# "SirSussusAmugus" = 4
# "SheSellSeaShellOnASeaShore" = 1
# "1234223432344234" = 1
s = input()
res = total_ways_to_split_strings(s)
print(res)
|
37a554bc933736bc95077e7050facefd4d5771e4 | EDU-FRANCK-JUBIN/exercices-sur-python-Nummytincan | /Ex5.py | 341 | 3.78125 | 4 | def minMaxMoy(list):
min = list[0]
max = list[0]
moy = list[0]
for i in range(1, len(list)-1):
moy += list[i]
if list[i] > max:
max = list[i]
if list[i] < min:
min = list[i]
moy /= len(list)
tuple = [min, max, moy]
print(tuple)
minMaxMoy([10, 18, 14, 20, 12, 16]) |
23321c2af3efa78ef1cc16eb827ca63f3e638a14 | I3lacx/Pythonbot | /Blacx/simpleNN_TensorFlow.py | 1,645 | 3.65625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 10
batch_size = 100 #so many into one iteration
#sets the shape so nothing goes wrong
x = tf.placeholder('float',[None, 784])
y = tf.placeholder('float')
def neural_network_model(data):
hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])), \
'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), \
'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), \
'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes]))}
#l1 = (data * weights1) + bias1
#activation function to normalize it
l1 = tf.add(tf.add(tf.matmul(data, hidden_1_layer['weights']),hidden_1_layer['biases']))
l1 = tf.nn.relu(l1)
l2 = tf.add(tf.add(tf.matmul(l1, hidden_2_layer['weights']),hidden_2_layer['biases']))
l2 = tf.nn.relu(l2)
l3 = tf.add(tf.add(tf.matmul(l2, hidden_3_layer['weights']),hidden_3_layer['biases']))
l3 = tf.nn.relu(l3)
output = tf.add(tf.add(tf.matmul(l3, output_layer['weights']),output_layer['biases']))
output = tf.nn.relu(output)
return output
|
43a3796979abae7ff9e192020e50d4d75fc10ab5 | GeertenRijsdijk/Theorie | /code/algorithms/random.py | 1,084 | 3.765625 | 4 | '''
random.py
Authors:
- Wisse Bemelman
- Michael de Jong
- Geerten Rijsdijk
This file implements the random algorithm which places houses randomly onto
the grid.
Parameters:
- grid: the grid object
Returns:
- None
'''
import numpy as np
from copy import copy
def random(grid):
# Randomly place houses
for i in range(grid.c):
# Choose the type of house to randomly place
choices = [j for j in range(len(grid.counts)) if grid.counts[j] > 0]
r = np.random.choice(choices)
grid.counts[r] -= 1
type = grid.house_types[r]
# Find locations where new house can be placed
free_spots = grid.find_spot(type)
xcoords, ycoords = np.where(free_spots == '.')
if len(xcoords) == 0:
print('NO SPACE LEFT AT', i, 'HOUSES!')
#visualize_map(free_spots)
break
# Choose random coordinates for the new house
r = np.random.randint(0, len(xcoords))
x, y = xcoords[r], ycoords[r]
# Place the house at the random coordinates
grid.place_house(type, x, y)
return
|
ffc1b07d67ac33e435dba906f1dea37bc304e508 | RandyHodges/Self-Study | /Python/Functions/funPractice.py | 964 | 4.21875 | 4 | # ======================= Play around with Python a bit ============================
#
# Create a new Python file in this folder called funcpractice.py.
# Inside it, create a function called 'addthree', that takes as input three parameters - num1, num2, num3.
# Then, write logic to create a new variable, y, that is the sum of all three of these numbers.
# Then, return the result y.
# Now, after you've defined this function, write a function call to return the sum of the numbers 52, 25, and 1403.
# Store this result in a variable called sumFunc.
# Print out sumFunc. Don't forget to cast to a String!
#
# ==================================================================================================
def addThree(num1, num2, num3):
total = int(num1) + int(num2) + int(num3)
return total
a = input("Please enter a: ")
b = input("Please enter b: ")
c = input("Please enter c: ")
print("Total equals: " + str(addThree(a, b, c))) |
ad7e40b80285c42ffa069c5e04c70809ef7ead46 | Illugi317/forritun | /mimir/12/4.py | 1,200 | 4.375 | 4 | '''
Write a program that accepts a list of integers, int_list, as an argument and a single integer, check_int, and then prints 'True' if two consecutive values of check_int are found in the int_list.
The program prints out an error message saying 'Error: enter only integers.' if the list is found to contain any non-numeric characters.
Examples:
Enter elements of list separated by commas: 2,3,4,4,5,6
Consecutive check: 4
True
Enter elements of list separated by commas: 2,3,4,5,6
Consecutive check: 4
False
Enter elements of list separated by commas: 2,3,5,8,8,x
Error: enter only integers.
'''
def take_input():
try:
numbers = input("Enter elements of list separated by commas: ")
return numbers.split(",")
except:
return None
def check(numlist):
for x in numlist:
if x.isnumeric():
pass
else:
return False
return True
numbers = take_input()
check = check(numbers)
if check is False:
print("Error: enter only integers.")
exit()
check_int = input("Consecutive check: ")
count = 0
for x in numbers:
if x == check_int:
count += 1
if count >= 2:
print("True")
else:
print("False")
|
8c0fe33540e47ca20c0da16af61ef9e44f7de0d7 | dorisli777/SSP2017-CUB | /orbitdet.py | 12,217 | 3.828125 | 4 | # This function gives the six orbital elements of an asteroid given a data file containing RA and DEC.
# Last modified August 2017 at the Summer Science Program in Boulder, CO
from math import *
#magnitude function
def mag(x):
y = 0
for i in x:
y = y + i**2
return sqrt(y)
#dot product function
def dot(x,y):
n = 0
i = 0
while i <= (len(x)-1):
n = x[i]*y[i] + n
i = i + 1
return n
#cross product function
def cross(x,y):
g = x[1]*y[2] - x[2]*y[1]
h = x[0]*y[2] - x[2]*y[0]
i = x[0]*y[1] - x[1]*y[0]
return g,-h,i
#angle checker
def angle_quad(sine, cosine):
angle1 = float(acos(cosine))
if sine >= 0 and cosine >= 0:
angle = angle1
if sine < 0 and cosine >= 0:
angle = (2*pi) - angle1
if sine >= 0 and cosine < 0:
angle = angle1
if sine < 0 and cosine < 0:
angle = pi - angle1
return angle
#find orbital elements function
def orbitalElements(r, rDot):
r0 = sqrt(r[0]**2 + r[1]**2 + r[2]**2)
v02 = dot(rDot,rDot)
a = 1/(2/r0 - v02)
print "Semi-Major Axis (a): ", a
rDot2 = (mag(cross(r,rDot)))**2
e = sqrt(1-(rDot2/a))
print "Eccentricity (e): ", e
hVec = cross(r,rDot)
i = atan(sqrt(hVec[0]**2+hVec[1]**2)/hVec[2]) * (180/pi)
print "Inclination (i): ", i
bigOmega = acos(-hVec[1]/(mag(hVec)*sin(i*pi/180))) * (180/pi)
print "Longitude of Ascending Node (big omega): ", bigOmega
cosv0 = (1/e)*((a*(1-e**2))/r0 - 1)
sinv0 = a*(1-e**2) / (e*mag(hVec))*dot(r,rDot)/r0
#define u (angle between ascending node and asteroid)
cosu0 = (r[0]*cos(bigOmega*(pi/180)) + r[1]*sin(bigOmega*pi/180))/r0
sinu01 = r[2]/(r0*sin(i*pi/180))
#check the sign of u0
u0 = angle_quad(sinu01,cosu0)
v0 = angle_quad(sinv0,cosv0)
#find argument of perihelion (angle between ascending node and perihelion)
w = (u0 - v0) % (2 * pi)
print "Argument of Perihelion (small omega): ", w * (180/pi)
E = acos(1/e*(1-mag(r)/a))
M = E - e*sin(E)
print "Mean Anomaly (M): ", M*(180/pi)
################################################
def orbitdet(fileName):
myFile = open(fileName,'r') #open file
myArr = []
num_rows = 0
#create array from file
for line in myFile:
myArr.append(line)
num_rows +=1
for row in range(0,num_rows):
myArr[row] = myArr[row].strip() #takes off the /n
myArr[row] = myArr[row].split() #splits the lines into an array
for i in range(0,3):
for j in range(0,13):
myArr[i][j] = float(myArr[i][j]) #change all the string elements in the array to floats
ra = []
dec = []
#changing ra and dec to decimal degrees
for i in range(0,3):
if myArr[i][0] > 0:
ra.append(radians((myArr[i][0]*15.) + (myArr[i][1]/4.) + (myArr[i][2]/240.)))
elif myArr[i][0] < 0:
ra.append(radians((myArr[i][0]*15.) - (myArr[i][1]/4.) - (myArr[i][2]/240.)))
if myArr[i][3] > 0:
dec.append(radians((myArr[i][3] + (myArr[i][4]/60.) + (myArr[i][5]/3600.))))
elif myArr[i][3] < 0:
dec.append((radians(myArr[i][3] - (myArr[i][4]/60.) - (myArr[i][5]/3600.))))
observation1 = myArr[0] #seperate lists for each observation
observation2 = myArr[1]
observation3 = myArr[2]
time1 = observation1[6] #in JD
time2 = observation2[6]
time3 = observation3[6]
RA1 = ra[0] #decimal hours
RA2 = ra[1]
RA3 = ra[2]
dec1 = dec[0] #decimal degrees
dec2 = dec[1]
dec3 = dec[2]
R1 = [observation1[7],observation1[8],observation1[9]] #sun vectors
R2 = [observation2[7],observation2[8],observation2[9]]
R3 = [observation3[7],observation3[8],observation3[9]]
cR1 = [observation1[7],observation1[8],observation1[9]] #sun vectors
cR2 = [observation2[7],observation2[8],observation2[9]]
cR3 = [observation3[7],observation3[8],observation3[9]]
vR1 = [observation1[10], observation1[11], observation1[12]] #sun velocity vectors
vR2 = [observation2[10], observation2[11], observation2[12]]
vR3 = [observation3[10], observation3[11], observation3[12]]
##find rho hat vector### (in AU)
p_hat1 = [cos(dec1)*cos(RA1), cos(dec1)*sin(RA1), sin(dec1)]
p_hat2 = [cos(dec2)*cos(RA2), cos(dec2)*sin(RA2), sin(dec2)]
p_hat3 = [cos(dec3)*cos(RA3), cos(dec3)*sin(RA3), sin(dec3)]
##find tau##
k = 0.01720209895
tau1 = k*(time1 - time2)
tau2 = k*(time3 - time1)
tau3 = k*(time3 - time2)
##find initial constants a1 and a3##
a1_ini = (time3 - time2)/(time3 - time1)
a3_ini = -(time1 - time2)/(time3 - time1)
#hairy triple vector products
D1 = dot(cross(p_hat1,p_hat2), p_hat3)
D2 = dot(cross(p_hat2,p_hat3), p_hat1)
D01 = dot(cross(R1, p_hat2), p_hat3)
D02 = dot(cross(R2, p_hat2), p_hat3)
D03 = dot(cross(R3, p_hat2), p_hat3)
D11 = dot(cross(p_hat1, R1), p_hat3)
D12 = dot(cross(p_hat1, R2), p_hat3)
D13 = dot(cross(p_hat1, R3), p_hat3)
D21 = dot(cross(p_hat2, R1), p_hat1)
D22 = dot(cross(p_hat2, R2), p_hat1)
D23 = dot(cross(p_hat2, R3), p_hat1)
##find rho vector magnitudes##
pmag1_ini= (a1_ini*D01 - D02 + a3_ini*D03) / (a1_ini*D2)
pmag2_ini = -(a1_ini*D11 - D12 + a3_ini*D13) / D2
pmag3_ini = (a1_ini*D21 - D22 + a3_ini*D23) / (a3_ini*D1)
##find rho vectors##
p1_ini = [pmag1_ini*p_hat1[0], pmag1_ini*p_hat1[1], pmag1_ini*p_hat1[2]]
p2_ini = [pmag2_ini*p_hat2[0], pmag2_ini*p_hat2[1], pmag2_ini*p_hat2[2]]
p3_ini = [pmag3_ini*p_hat3[0], pmag3_ini*p_hat3[1], pmag3_ini*p_hat3[2]]
######LIGHT CORRECTION#####
c = 173.1446 #in AU per day
time1new = time1 - pmag1_ini/c
time2new = time2 - pmag2_ini/c
time3new = time3 - pmag3_ini/c
#another way to write pmag/c (change in time)
x1 = time1new - time1
x2 = time2new - time2
x3 = time3new - time3
#correct for sun vector
cR1 = [(R1[0] + x1*vR1[0]), R1[1] + x1*vR1[1], R1[2] + x1*vR1[2]]
cR2 = [(R2[0] + x2*vR2[0]), R2[1] + x2*vR2[1], R2[2] + x2*vR2[2]]
cR3 = [(R3[0] + x3*vR3[0]), R3[1] + x3*vR3[1], R3[2] + x3*vR3[2]]
#correct tau values
tau1 = k*(time1new - time2new)
tau2 = k*(time3new - time1new)
tau3 = k*(time3new - time2new)
##find position vectors (r = p - R) ###
r1_ini = [p1_ini[0] - cR1[0], p1_ini[1] - cR1[1], p1_ini[2] - cR1[2]]
r2_ini = [p2_ini[0] - cR2[0], p2_ini[1] - cR2[1], p2_ini[2] - cR2[2]] #r0
r3_ini = [p3_ini[0] - cR3[0], p3_ini[1] - cR3[1], p3_ini[2] - cR3[2]]
magr2_i = mag(r2_ini)
#find r dot vector
rdot_ini = [(r3_ini[0] - r1_ini[0])/tau2, (r3_ini[1] - r1_ini[1])/tau2, (r3_ini[2] - r1_ini[2])/tau2,]
##f and g initial guesses##
f1_ini = 1 - (tau1**2)/(2*magr2_i**3) + dot(rdot_ini, r2_ini)*(tau1**3)/(2*magr2_i**5)
g1_ini = tau1 - ((tau1**3)/(6*(magr2_i**3)))
f3_ini = 1 - (tau3**2)/(2*magr2_i**3) + dot(rdot_ini, r2_ini)*(tau3**3)/(2 * magr2_i**5)
g3_ini = tau3 - ((tau3**3)/(6*(magr2_i**3)))
#find new values of constants
a1 = g3_ini/(f1_ini*g3_ini - f3_ini*g1_ini)
a3 = -g1_ini/(f1_ini*g3_ini - f3_ini*g1_ini)
#find new magnitudes with new a constants
pmag1 = (a1*D01 - D02 + a3*D03)/(a1*D2)
pmag2 = -(a1*D11 - D12 + a3*D13)/D2
pmag3 = (a1*D21 - D22 + a3*D23)/(a3*D1)
#new rho vectors
p1 = [pmag1*p_hat1[0], pmag1*p_hat1[1], pmag1*p_hat1[2]]
p2 = [pmag2*p_hat2[0], pmag2*p_hat2[1], pmag2*p_hat2[2]]
p3 = [pmag3*p_hat3[0], pmag3*p_hat3[1], pmag3*p_hat3[2]]
#######LIGHT CORRRECTION#######
time1new = time1 - pmag1/c
time2new = time2 - pmag2/c
time3new = time3 - pmag3/c
#another way to write pmag/c (time difference)
x1 = time1new - time1
x2 = time2new - time2
x3 = time3new - time3
#correct for sun vector
cR1 = [(R1[0] + x1*vR1[0]), R1[1] + x1*vR1[1], R1[2] + x1*vR1[2]]
cR2 = [(R2[0] + x2*vR2[0]), R2[1] + x2*vR2[1], R2[2] + x2*vR2[2]]
cR3 = [(R3[0] + x3*vR3[0]), R3[1] + x3*vR3[1], R3[2] + x3*vR3[2]]
#new tau values
tau1 = k*(time1new - time2new)
tau2 = k*(time3new - time1new)
tau3 = k*(time3new - time2new)
##find position vectors ##
r1 = [p1[0] - cR1[0], p1[1] - cR1[1], p1[2] - cR1[2]]
r2 = [p2[0] - cR2[0], p2[1] - cR2[1], p2[2] - cR2[2]] #r0
r3 = [p3[0] - cR3[0], p3[1] - cR3[1], p3[2] - cR3[2]]
magr2 = mag(r2)
#find r dot vectors
rdot = [(r3[0] - r1[0])/tau2, (r3[1] - r1[1])/tau2, (r3[2] - r1[2])/tau2]
#another f and g series to make values of r and r dot more precise
f1 = 1 - (tau1**2)/(2*magr2**3) + dot(rdot, r2)*(tau1**3)/(2*magr2**5) #f is dimensionless
g1 = tau1 - ((tau1**3)/(6 * (magr2**3))) #g has units of time
f3 = 1 - (tau3**2)/(2*magr2**3) + dot(rdot, r2)*(tau3**3)/(2*magr2**5)
g3 = tau3 - ((tau3**3)/(6*(magr2**3)))
#find r dot vector
c1 = f3/(g1*f3 - g3*f1)
c2 = f1/(g1*f3 - g3*f1)
rdot = [c1*r1[0] - c2*r3[0], c1*r1[1] - c2*r3[1], c1*r1[2] - c2*r3[2]]
##iteration loop for r and rdot vectors##
r1f = [] #set empty final lists for r position vector
r3f = []
count = 0 #set a counter for number of iterations
while abs(magr2 - mag(r2_ini)) != 0:
count += 1
r2_ini = r2 #sets the new value to the "old" value
#f and g series
f1 = 1 - (tau1**2)/(2*magr2**3) + dot(rdot, r2)*(tau1**3)/(2*magr2**5) #f is dimensionless
g1 = tau1 - ((tau1**3)/(6*(magr2**3))) #g has units of time
f3 = 1 - (tau3**2)/(2*magr2**3) + dot(rdot, r2)*(tau3**3)/(2*magr2**5)
g3 = tau3 - ((tau3**3)/(6*(magr2**3)))
#new a constants
a1 = g3/(f1*g3 - f3*g1)
a3 = -g1/(f1*g3 - f3*g1)
#new magnitude vectors
pmag1 = (a1*D01 - D02 + a3*D03)/(a1*D2)
pmag2 = -(a1*D11 - D12 + a3*D13)/D2
pmag3 = (a1*D21 - D22 + a3*D23)/(a3*D1)
#########rho vectors########
p1 = [pmag1*p_hat1[0], pmag1*p_hat1[1], pmag1*p_hat1[2]]
p2 = [pmag2*p_hat2[0], pmag2*p_hat2[1], pmag2*p_hat2[2]]
p3 = [pmag3*p_hat3[0], pmag3*p_hat3[1], pmag3*p_hat3[2]]
time1new = time1 - pmag1/c
time2new = time2 - pmag2/c
time3new = time3 - pmag3/c
#another way to write pmag/c (change in time)
x1 = time1new - time1
x2 = time2new - time2
x3 = time3new - time3
#correct for sun vector
cR1 = [(R1[0] + x1*vR1[0]), R1[1] + x1*vR1[1], R1[2] + x1*vR1[2]]
cR2 = [(R2[0] + x2*vR2[0]), R2[1] + x2*vR2[1], R2[2] + x2*vR2[2]]
cR3 = [(R3[0] + x3*vR3[0]), R3[1] + x3*vR3[1], R3[2] + x3*vR3[2]]
tau1 = k*(time1new - time2new)
tau2 = k*(time3new - time1new)
tau3 = k*(time3new - time2new)
#####END OF LIGHT #######
#find position vectors
r1f = [p1[0] - cR1[0], p1[1] - cR1[1], p1[2] - cR1[2]]
r2 = [p2[0] - cR2[0], p2[1] - cR2[1], p2[2] - cR2[2]]
r3f = [p3[0] - cR3[0], p3[1] - cR3[1], p3[2] - cR3[2]]
magr2 = mag(r2)
#find r dot vector
c1 = f3/(g1*f3 - g3*f1)
c2 = f1/(g1*f3 - g3*f1)
rdot = [c1*r1f[0] - c2*r3f[0], c1*r1f[1] - c2*r3f[1], c1*r1f[2] - c2*r3f[2]]
print "r2 Vector: ", r2
print "rdot Vector: ", rdot
print "Number of iterations: ", count
#convert from equatorial to ecliptic
epsilon = 0.4090926277
#rotation matrix for r position vector
xEcl = r2[0]
yEcl = r2[1]*cos(-epsilon) - r2[2]*sin(-epsilon)
zEcl = r2[1]*sin(-epsilon) + r2[2]*cos(-epsilon)
rEcl = [xEcl, yEcl, zEcl]
#rotation matrix for r dot (velocity) vector
xEcl1 = rdot[0]
yEcl1 = rdot[1]*cos(-epsilon) - rdot[2]*sin(-epsilon)
zEcl1 = rdot[1]*sin(-epsilon) + rdot[2]*cos(-epsilon)
rdotEcl = [xEcl1, yEcl1, zEcl1]
print rEcl, rdotEcl
#call orbital elements function
orbitalElements(rEcl, rdotEcl)
#own asteroid
orbitdet("asterorbit.txt")
#test data
#orbitdet("orbitdet.txt")
|
ecf06c6339c380da9b64e2ef5e8a83f6568d60d8 | oktavianidewi/interactivepython | /ss_bubblesort.py | 551 | 3.796875 | 4 | def diyBubbleSort(alist):
for iterasiEksternal in reversed(range(len(alist))):
print iterasiEksternal
for nilaiInternal in range(iterasiEksternal):
if alist[nilaiInternal] > alist[nilaiInternal+1]:
temp = alist[nilaiInternal]
alist[nilaiInternal] = alist[nilaiInternal+1]
alist[nilaiInternal+1] = temp
print alist
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
blist = [19, 1, 9, 7, 3, 10, 13, 15, 8, 12]
# bubbleSort(blist)
diyBubbleSort(blist)
# print alist |
118a576d61e57beb2a8dcda493f41811995da387 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/mtsmol017/question4.py | 384 | 3.765625 | 4 | b=eval(input("Enter the starting point N:\n"))
c=eval(input("Enter the ending point M:\n"))
result=[]
for i in range(b,c):
if str(i)==(str(i))[-1::-1]:
factors=0
for m in range(2,10):
if i%m==0:
factors+=1
if factors<1:
result.append(i)
print("The palindromic primes are:")
for p in result:
print(p) |
c96ca87da9d987a46c17b78e5c9d9398202a9f78 | xliang01/AlgoExpertChallenges | /Easy/closestValueBST.py | 1,687 | 3.65625 | 4 | import sys
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = BST(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
else:
self.right.insert(value)
return self
# T: O(NLogN), Worst O(N)
# S: O(NLogN), Worst O(N)
# def findClosestValueInBst(tree, target):
# return findClosestValueInBstHelper(tree, target, float("inf"))
# def findClosestValueInBstHelper(tree, target, closest):
# if tree is None:
# return closest
# elif abs(target - tree.value) < abs(target - closest):
# closest = tree.value
# if target > tree.value:
# return findClosestValueInBstHelper(tree.right, target, closest)
# elif target < tree.value:
# return findClosestValueInBstHelper(tree.left, target, closest)
# else:
# return closest
# T: O(NLogN), Worst: O(N)
# S: O(1), Worst: O(1)
def findClosestValueInBst(tree, target):
curr = tree
closest = float("inf")
while curr is not None:
if abs(target - curr.value) < abs(target - closest):
closest = curr.value
if target > curr.value:
curr = curr.right
elif target < curr.value:
curr = curr.left
else:
break
return closest
test = BST(10).insert(5).insert(2).insert(5).insert(1).insert(15).insert(13).insert(14).insert(22)
ans = findClosestValueInBst(test, 12)
print(ans)
|
b19a08c6773244feead303fd3c29b01933c6f535 | SimonJang/advent-of-code-2019 | /day2.py | 2,480 | 3.640625 | 4 | def execute_operation(operation: int, a: int, b: int) -> int:
if operation is 1:
return a + b
if operation is 2:
return a * b
if operation is 99:
return None
print(f"Exception operation: {operation}")
raise Exception
def day1():
with open('./data/day2.txt') as file:
for line in file:
instructions = line.split(',')
instructions = [int(instruction) for instruction in instructions]
instructions[1] = 12
instructions[2] = 2
index = 0
while True:
operation = instructions[index]
value_a = instructions[instructions[index + 1]]
value_b = instructions[instructions[index + 2]]
store_location = instructions[index + 3]
if operation is 99:
print(f"First number is: {instructions[0]}")
break
result = execute_operation(operation, value_a, value_b)
instructions[store_location] = result
index = index + 4
# day1()
def day2():
with open('./data/day2.txt') as file:
for line in file:
instructions = line.split(',')
instructions = [int(instruction) for instruction in instructions]
parameters = [tuple([x, y]) for x in range(0, 100) for y in range(0, 100)]
checksum = 19690720
for a, b in parameters:
calculated_instructions = instructions.copy()
index = 0
calculated_instructions[1] = a
calculated_instructions[2] = b
while True:
operation = calculated_instructions[index]
value_a = calculated_instructions[calculated_instructions[index + 1]]
value_b = calculated_instructions[calculated_instructions[index + 2]]
store_location = calculated_instructions[index + 3]
result = execute_operation(operation, value_a, value_b)
if result is None:
if calculated_instructions[0] == checksum:
print(f"{calculated_instructions[0]} | {checksum}")
print(f"Checksum match: {100 * a + b}")
break
calculated_instructions[store_location] = result
index = index + 4
day2()
|
796d371d812915500f17495888310d6839e93754 | OrangeHoodie240/SB_Captstone_One | /utility.py | 1,392 | 3.65625 | 4 | import datetime as dt
import random
import math
weekdays = {'monday': 1, 'tuesday': 2, 'wednesday': 3, 'thursday': 4, 'friday': 5, 'saturday': 6, 'sunday': 7}
def find_closest_workout(workout):
weekday = dt.datetime.today().weekday() + 1
closest = 8
closest_day = None
for day in workout.days:
workout_on = weekdays[day.weekday]
distance = None
if workout_on > weekday:
distance = workout_on - weekday
elif weekday > workout_on:
distance = 7 - weekday + workout_on
else:
return day
if distance < closest:
closest = distance
closest_day = day
return closest_day
def quicksort(arr, attr=None):
n = len(arr)
if n == 0 or n == 1:
return arr
rand = int(math.floor(random.random() * n))
bench = None
if attr is None:
bench = arr[rand]
else:
bench = getattr(arr[rand], attr)
left = []
right = []
for i in range(n):
current = None
if attr is None:
current = arr[i]
else:
current = getattr(arr[i], attr)
if current < bench:
left.append(arr[i])
elif current > bench:
right.append(arr[i])
return [*quicksort(left, attr=attr), arr[rand], *quicksort(right, attr=attr)]
|
fe3a4562a519cc6186805177db345b4a71b660cf | anttilip/telepybot | /telepybot/modules/weather.py | 9,604 | 3.59375 | 4 | """*Returns weather forecast for a location.*
This module can search weather reports using Wunderground API.
Weather reports consist of a current weather in observation location,
a 3 day weather forecast and distance from observation location to
the requested location. Module also features an interactive mode where user
can search new locations relative to the original location.
Usage:
```
/weather
/weather Palo Alto, CA
```
Interactive mode:
```
[distance] [cardinal direction]
100 NW - weather in 100km to northwest from original location
```
"""
import json
from math import asin, atan2, cos, degrees, pi, radians, sin, sqrt
#from telegram import KeyboardButton, ParseMode, ReplyKeyboardMarkup
import telegram
from geopy.geocoders import Nominatim
try:
# For Python 3.0 and later
from urllib.request import urlopen
from configparser import ConfigParser
except ImportError:
# Fall back to Python 2's urllib
from urllib import urlopen
from ConfigParser import ConfigParser
config = ConfigParser()
config.read('telepybot.conf')
api_key = config.get('weather', 'wundergroundApiKey')
def handle_update(bot, update, update_queue, logger):
"""Get weather forecast for location from update.
This is the main function that modulehander calls.
Args:
bot (telegram.Bot): Telegram bot itself
update (telegram.Update): Update that will be processed
update_queue (Queue): Queue containing all incoming and unhandled updates
logger (Logger): Logger that writes to bots own log file.
"""
chat_id = update.message.chat_id
bot.sendChatAction(chat_id, action=telegram.ChatAction.TYPING)
try:
command = update.message.text.split(' ', 1)[1]
except IndexError:
command = ''
finally:
message = update.message
location = None
while not location:
#text = ("Please send a location or type a city.\nYou may also "
# "cancel by typing \"cancel\"")
text = "Please send a location or type a city."
if message.location:
reply_markup = telegram.ReplyKeyboardHide()
bot.sendMessage(
chat_id=chat_id,
text="Searching forecast.",
reply_markup=reply_markup)
bot.sendChatAction(chat_id, action=telegram.ChatAction.TYPING)
location = parse_location(message.location)
elif command != '':
if command.lower() == 'cancel':
reply_markup = telegram.ReplyKeyboardHide()
bot.sendMessage(
chat_id=chat_id,
text="Cancelled.",
reply_markup=reply_markup)
return
try:
geolocator = Nominatim()
geo_code = geolocator.geocode(command)
if not geo_code:
raise ValueError("geolocator.geocode() returned None")
reply_markup = telegram.ReplyKeyboardHide()
bot.sendMessage(
chat_id=chat_id,
text="Searching forecast.",
reply_markup=reply_markup)
location = parse_location(geo_code)
except ValueError as e:
logger.info("location %s caused error %s" % (command, e))
text = "Couldn't find that location. Try anothet location"
bot.sendMessage(chat_id=chat_id, text=text)
message = update_queue.get().message
if message.text.startswith('/'):
# User accesses antoher module
update_queue.put(update)
return
command = message.text
bot.sendChatAction(chat_id, action=telegram.ChatAction.TYPING)
# TODO: fix this horrible structure
else:
location_keyboard = telegram.KeyboardButton(
text='Send location', request_location=True)
reply_markup = telegram.ReplyKeyboardMarkup(
[[location_keyboard], ['Cancel']])
bot.sendMessage(
chat_id=chat_id, text=text, reply_markup=reply_markup)
message = update_queue.get().message
if message.text.startswith('/'):
# User accesses antoher module
update_queue.put(update)
return
command = message.text
bot.sendChatAction(chat_id, action=telegram.ChatAction.TYPING)
report = construct_report(location)
bot.sendMessage(
chat_id=chat_id, text=report, parse_mode=telegram.ParseMode.MARKDOWN)
# Interactive mode, where user can change location e.g. "100 N"
text = """To search weather for relative position,
type [distance in km] [direction], e.g. "100 N"."""
bot.sendMessage(chat_id=chat_id, text=text)
while True:
update = update_queue.get()
bot.sendChatAction(chat_id, action=telegram.ChatAction.TYPING)
try:
distance, direction = update.message.text.split()
distance = int(distance)
new_location = calculate_new_query(location, distance, direction)
bot.sendMessage(
chat_id=chat_id,
text=construct_report(new_location),
parse_mode=telegram.ParseMode.MARKDOWN)
except ValueError:
if update.message.text.startswith('/'):
# User accesses antoher module
update_queue.put(update)
else:
text = "Invalid command. Interaction stopped"
bot.sendMessage(chat_id=chat_id, text=text)
break
def construct_report(query):
"""Construct the weather report that will be sent to user."""
response = urlopen('http://api.wunderground.com/api/' + api_key +
'/conditions/forecast/alert/q/' + query + '.json')
# Python 3 compatibility
response_str = response.read().decode('utf-8')
text = json.loads(response_str)
try:
error = text['response']['error']['type']
if error == 'querynotfound':
return "Sorry, couldn't fetch weather report from that location"
except KeyError:
pass
curr = text['current_observation']
distance = calculate_distance(
float(query.split(',')[1]), float(query.split(',')[0]),
float(curr['observation_location']['longitude']),
float(curr['observation_location']['latitude']))
bearing = calculate_direction(
float(query.split(',')[0]), float(query.split(',')[1]),
float(curr['observation_location']['latitude']),
float(curr['observation_location']['longitude']))
# Build report which contains location, current observation etc.
report = ('*{}*\nAccuracy: {}km {}\n{}\n{}, {}C, {}km/h, '
'{}mm past hour\n\n').format(
curr['observation_location']['full'], distance, bearing,
curr['observation_time'], curr['weather'], curr['temp_c'],
curr['wind_kph'], curr['precip_1hr_metric'])
forecast = text['forecast']['txt_forecast']['forecastday']
# Forecast for several time periods
for i in range(1, 8):
report += '*{}:* {} Probability for precipitation: {}%\n\n'.format(
forecast[i]['title'], forecast[i]['fcttext_metric'],
forecast[i]['pop'])
return report
def calculate_distance(lon1, lat1, lon2, lat2):
"""Calculate the great circle distance between two
coordinate points
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * asin(sqrt(a))
r = 6371 # earth radius in km
return "{0:.2f}".format(r * c) # Leave two decimals and convert to string
def calculate_direction(lat1, lon1, lat2, lon2):
"""Calculate compass bearing from starting point to
the end point and then convert it to a cardinal direction.
"""
lat1rad = radians(lat1)
lat2rad = radians(lat2)
dlon = radians(lon2 - lon1)
x = sin(dlon) * cos(lat2rad)
y = cos(lat1rad) * sin(lat2rad) - sin(lat1rad) * cos(lat2rad) * cos(dlon)
init_bearing = degrees(atan2(x, y))
compass_bearing = init_bearing % 360
directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"]
i = int(round(compass_bearing / 45))
return directions[i]
def calculate_new_query(old_query, distance, direction):
"""Find new location from interactive mode."""
angle = {
'N': 0,
'NE': pi / 4,
'E': pi / 2,
'SE': 3 * pi / 4,
'S': pi,
'SW': 5 * pi / 4,
'W': 3 * pi / 2,
'NW': 7 * pi / 4
}
r = 6371 # earth radius in km
dist = float(distance) / r # angular distance
old_lat, old_lon = old_query.split(',')
old_lat = radians(float(old_lat))
old_lon = radians(float(old_lon))
new_lat = asin(
sin(old_lat) * cos(dist) + cos(old_lat) * sin(dist) * cos(angle[
direction.upper()]))
new_lon = old_lon + atan2(
sin((angle[direction.upper()])) * sin(dist) * cos(old_lat), cos(dist) -
sin(old_lat) * sin(new_lat))
return '{},{}'.format(degrees(new_lat), degrees(new_lon))
def parse_location(location):
"""Convert location to string, e.g. "60.161928,24.951688"
"""
return str(location.latitude) + ',' + str(location.longitude)
|
36f1dad1209bb1f575fca85d536011663f473a33 | ChWeiking/PythonTutorial | /Python基础/day11(继承、多态、类属性、类方法、静态方法)/demo/03_类属性/02_类属性.py | 1,079 | 4.1875 | 4 | '''
类属性:
1、定义在类内部,方法外部的属性就是类属性
2、在类的外部,通过类对象.属性就是类属性
类属性是属于类对象的,还属于所有实例对象
'''
class Dog:
name = '子庆'
color = '黑色'
num=123456
def run(self):
print('run...')
'''
d1 = Dog()
d1.name = '旺财'
print(d1.name)
print(dir(Dog))
print(Dog.name)
Dog.sex = '雄'
print(Dog.sex)
print(dir(Dog))
print(d1.sex)
'''
d1 = Dog()
d2 = Dog()
print(d1.name)
print(d2.name)
Dog.name = '旺财'
print(d1.name)
print(d2.name)
'''
d1 = Dog()
d2 = Dog()
print(d1.name)
print(d2.name)
#此时name是一个实例属性
d1.name = '旺财'
print(d1.name)
print(d2.name)
'''
'''
d1 = Dog()
print(id(Dog.name))
print(id(d1.name))
print(Dog.run)
print(d1.run)
print(d2.run)
'''
'''
d1 = Dog()
d2 = Dog()
def stop(self):
print('stop...')
Dog.stop = stop
print(Dog.stop)
d1.stop()
print(id(d1.stop))
print(id(d2.stop))
print(id(Dog.stop))
'''
'''
d1 = Dog()
d2 = Dog()
def stop(self):
print('stop...')
Dog.run = stop
d1.run()
'''
|
e527a551b17d706c206afc1285fe6c319aabbeda | NagaTaku/atcoder_abc_edition | /ABC066/b.py | 197 | 3.546875 | 4 | s = input()
s_len = len(s)
for i in range(1, int(s_len/2)+1):
s = s[:-2]
half = int(len(s)/2)
s_mae = s[:half]
s_ato = s[half:]
if s_mae == s_ato:
break
print(len(s)) |
694bd775680ac62ddca32c15bad3e73072495a65 | moecherry99/GraphTheory | /shunting.py | 674 | 3.5625 | 4 | # Alex Cherry - G00347106
# Shunting Yard Algorithm
def shunting(infix):
specials = {'*': 50, '.': 40, '|': 30}
pofix = ""
stack1 = ""
for c in infix:
if c == '(':
stack1 = stack1 + c
elif c == ')':
while stack1[-1] != '(':
pofix, stack1 = pofix + stack1[-1], stack1[:-1]
stack1 = stack1[:-1]
elif c in specials:
while stack1 and specials.get(c, 0) <= specials.get(stack1[-1], 0):
pofix, stack1 = pofix + stack1[-1], stack1[:-1]
stack1 = stack1 + c
else:
pofix = pofix + c
while stack1:
pofix, stack1 = pofix + stack1[-1], stack1[:-1]
return pofix
print(shunting("(a.b)|(c*.d)"))
|
52a63b37fe7c1beb20b5f9566a824ca10620db03 | saicharantejaDoddi/COMP_6411_GuessGame | /game.py | 4,567 | 4.03125 | 4 |
class Game:
"""
The Game object provides the scheme to store the individual game.
Parameters:
----------
No parameters are passed.
Attributes:
----------
GameNo(int):The is where we store current game number.
Word(str):The is where we store current guessing word.
Status(str):The is where we store Status of the current game.
BadGuess(int):The is where we store number of bad guess by the user in the curret game.
MissedLetters(int):The is where we store number of missed guess letters by the usere in the current game.
Totalrequestletters(int):The is where we store Total number of the guess letters by the user in the current game.
Score(int):The is where we store Score of the user in the current game.
"""
GameNo=0
Word=""
Status=""
BadGuess=0
MissedLetters=0
Totalrequestletters=0;
Score=0
def intialize(self,currGameNo,currWord,currStatus,currBadGuess,currMissedLetters,currTotalrequestletters,currScore):
""" This function fills the details to used for the reporting.
parameters:
currGameNo(int):The current game number.
currWord(str):The current guessing word.
currStatus(str):The Status of the current game.
currBadGuess(int):The number of bad guess by the user in the curret game.
currMissedLetters(int):The number of missed guess letters by the usere in the current game.
currTotalrequestletters(int):The Total number of the guess letters by the user in the current game.
currScore(int):The Score of the user in the current game.
Nothing.
Returns:
Nothing.
"""
self.GameNo=currGameNo
self.Word=currWord
self.Status=currStatus
self.BadGuess=currBadGuess
self.MissedLetters=currMissedLetters
self.Totalrequestletters=currTotalrequestletters
self.Score=currScore
return
listofreport=[]
pointsTable=[]
def addGameReport(currGameNo,currWord,currStatus,currBadGuess,currMissedLetters,currTotalrequestletters,currScore):
""" This function add Single games to the final report collection.
parameters:
currGameNo(int):The current game number.
currWord(str):The current guessing word.
currStatus(str):The Status of the current game.
currBadGuess(int):The number of bad guess by the user in the curret game.
currMissedLetters(int):The number of missed guess letters by the usere in the current game.
currTotalrequestletters(int):The Total number of the guess letters by the user in the current game.
currScore(int):The Score of the user in the current game.
Nothing.
Returns:
Nothing.
"""
Gameobj=Game()
if(int(currTotalrequestletters)==0):
currScore=currScore
else:
currScore=(currScore)/(currTotalrequestletters)
if (int(currBadGuess) == 0):
currScore = currScore
else:
currScore = currScore - currScore * (((currBadGuess * 10) / 100))
Gameobj.intialize(currGameNo,currWord,currStatus,currBadGuess,currMissedLetters,currTotalrequestletters,currScore)
listofreport.append(Gameobj)
def printer():
""" This function prints the score report of the user.
parameters:
Nothing.
Returns:
Nothing.
"""
print("Game Word Status Bad Guesses Missed Letters Score")
print("---- ---- ------ ----------- -------------- -----")
for Game in listofreport:
print(str(Game.GameNo)+" "+str(Game.Word)+" "+str(Game.Status)+" "+str(Game.BadGuess)+" "
+str(Game.MissedLetters)+" "+str(int(Game.Score)))
|
628aa689b89323a24ad7f84ca67ab28fa9e63ba9 | AkeBoss-tech/chessEngine | /Screen.py | 14,461 | 3.625 | 4 | import pygame, random, math, time, os
def drawRectangle(screen, color, x, y, width=100, height=100):
pygame.draw.rect(screen, color, (x, y, width, height))
def drawHollowCircle(screen, color, radius, center_x, center_y):
iterations = 100
for i in range(iterations):
ang = i * 3.14159 * 2 / iterations
dx = int(math.cos(ang) * radius)
dy = int(math.sin(ang) * radius)
x = center_x + dx
y = center_y + dy
pygame.draw.circle(screen, color, (x, y), 5)
def drawCircle(screen, color, x, y, width, height):
rect = [x, y, width, height]
pygame.draw.ellipse(screen, color, rect, 0)
def writeText(text, screen, X, Y, color=(0, 0, 0), fontSize=64):
# create a font object.
# 1st parameter is the font file
# which is present in pygame.
# 2nd parameter is size of the font
font = pygame.font.Font('freesansbold.ttf', fontSize)
# create a text surface object,
# on which text is drawn on it.
text = font.render(text, True, color)
# create a rectangular object for the
# text surface object
textRect = text.get_rect()
# set the center of the rectangular object.
textRect.center = (X, Y)
screen.blit(text, textRect)
class screen():
def __init__(self):
self.screenHeight = 950
self.screenWidth = 950
self.white = (255, 255, 255)
self.black = (38, 38, 38)
self.pureBlack = (1, 4, 105)
self.gray = (166, 166, 166)
self.red = (207, 0, 0)
self.blue = (7, 219, 131)
self.lightGreen = (210, 235, 52)
self.green = (10, 186, 7)
self.screen = pygame.display.set_mode((self.screenWidth, self.screenHeight))
path = os.path.dirname(os.path.realpath(__file__))
path = path + r"\icons"
self.wQ = pygame.image.load(str(path) + r"\wQ.png")
self.wQ = pygame.transform.rotozoom(self.wQ, 0, 1.5)
self.wK = pygame.image.load(str(path) + r"\wK.png")
self.wK = pygame.transform.rotozoom(self.wK, 0, 1.5)
self.wN = pygame.image.load(str(path) + r"\wN.png")
self.wN = pygame.transform.rotozoom(self.wN, 0, 1.5)
self.wR = pygame.image.load(str(path) + r"\wR.png")
self.wR = pygame.transform.rotozoom(self.wR, 0, 1.5)
self.wp = pygame.image.load(str(path) + r"\wp.png")
self.wp = pygame.transform.rotozoom(self.wp, 0, 1.5)
self.wB = pygame.image.load(str(path) + r"\wB.png")
self.wB = pygame.transform.rotozoom(self.wB, 0, 1.5)
self.bQ = pygame.image.load(str(path) + r"\bQ.png")
self.bQ = pygame.transform.rotozoom(self.bQ, 0, 1.5)
self.bK = pygame.image.load(str(path) + r"\bK.png")
self.bK = pygame.transform.rotozoom(self.bK, 0, 1.5)
self.bN = pygame.image.load(str(path) + r"\bN.png")
self.bN = pygame.transform.rotozoom(self.bN, 0, 1.5)
self.bR = pygame.image.load(str(path) + r"\bR.png")
self.bR = pygame.transform.rotozoom(self.bR, 0, 1.5)
self.bp = pygame.image.load(str(path) + r"\bp.png")
self.bp = pygame.transform.rotozoom(self.bp, 0, 1.5)
self.bB = pygame.image.load(str(path) + r"\bB.png")
self.bB = pygame.transform.rotozoom(self.bB, 0, 1.5)
pygame.display.set_caption('Chess Engine')
def welcomeScreen(self):
self.screen.fill(self.black)
for i in range(15):
drawCircle(self.screen, self.white, random.randint(0,950), random.randint(0,950), 5, 5)
writeText("Checkers", self.screen, 450, 60, self.white)
drawRectangle(self.screen, self.gray, 250, 350, 400, 150)
drawRectangle(self.screen, self.gray, 250, 650, 400, 150)
drawRectangle(self.screen, self.gray, 750, 0, 200, 100)
writeText("View", self.screen, 455, 425, self.white)
writeText("Play", self.screen, 455, 725, self.white)
writeText("Help", self.screen, 850, 50, self.white)
writeText("By: Akash Dubey", self.screen, 650, 900, self.white)
pygame.display.update()
def playScreen(self):
self.screen.fill(self.black)
for i in range(10):
drawCircle(self.screen, self.white, random.randint(0,950), random.randint(0,950), 5, 5)
writeText("Play", self.screen, 450, 60, self.white)
drawRectangle(self.screen, self.gray, 250, 350, 400, 150)
drawRectangle(self.screen, self.gray, 250, 750, 400, 100)
drawRectangle(self.screen, self.gray, 250, 550, 400, 150)
writeText("COMPUTER", self.screen, 455, 425, self.white)
writeText("HUMAN", self.screen, 455, 625, self.white)
writeText("BACK", self.screen, 455, 800, self.white)
writeText("vs.", self.screen, 450, 200, self.white)
pygame.display.update()
def viewScreen(self, text, subText=""):
self.screen.fill(self.black)
for i in range(10):
drawCircle(self.screen, self.white, random.randint(0,950), random.randint(0,950), 5, 5)
writeText(text, self.screen, 455, 260, self.white)
writeText(subText, self.screen, 450, 425, self.white)
writeText("Click to advance", self.screen, 455, 625, self.white)
pygame.display.update()
def endScreen(self):
self.screen.fill(self.black)
for i in range(15):
drawCircle(self.screen, self.white, random.randint(0,950), random.randint(0,950), 5, 5)
writeText("Save the game?", self.screen, 450, 160, self.white)
drawRectangle(self.screen, self.gray, 250, 350, 400, 150)
drawRectangle(self.screen, self.gray, 250, 650, 400, 150)
writeText("Yes", self.screen, 455, 425,self. white)
writeText("No", self.screen, 455, 725, self.white)
pygame.display.update()
def chooseComputerScreen(self):
self.screen.fill(self.black)
for i in range(15):
drawCircle(self.screen, self.white, random.randint(0,950), random.randint(0,950), 5, 5)
writeText("Computer Menu", self.screen, 450, 60, self.white)
drawRectangle(self.screen, self.gray, 50, 250, 400, 250) # Random
drawRectangle(self.screen, self.gray, 500, 250, 400, 250) # Easy
drawRectangle(self.screen, self.gray, 50, 550, 400, 250) # Medium
drawRectangle(self.screen, self.gray, 500, 550, 400, 250) # Hard
drawRectangle(self.screen, self.gray, 50, 825, 850, 100) # UNDO
writeText("RANDOM", self.screen, 50+180, 250+130, self.white)
writeText("EASY", self.screen, 500+185, 250+130, self.white)
writeText("MEDIUM", self.screen, 250, 675, self.white)
writeText("HARD", self.screen, 690, 675, self.white)
writeText("BACK", self.screen, 455, 885, self.white)
pygame.display.update()
def confirmScreen(self, text, subText=""):
self.screen.fill(self.black)
for i in range(15):
drawCircle(self.screen, self.white, random.randint(0,950), random.randint(0,950), 5, 5)
writeText(text, self.screen, 450, 160, self.white)
writeText(subText, self.screen, 450, 260, self.white)
drawRectangle(self.screen, self.gray, 250, 350, 400, 150)
drawRectangle(self.screen, self.gray, 250, 650, 400, 150)
writeText("Yes", self.screen, 455, 425, self.white)
writeText("No", self.screen, 455, 725,self.white)
pygame.display.update()
def drawGrid(self, board, highlightList):
screen = self.screen
screen.fill((162, 163, 162))
colorsGrid = [
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1]
]
drawRectangle(screen, self.green, 0, 0)
white = (255, 255, 255)
black = (125, 51, 2)
gray = (166, 166, 166)
red = (255, 0, 0)
blue = (7, 219, 131)
green = (10, 186, 7)
bufferX = 0
bufferY = 0
for a, r in enumerate(colorsGrid):
for b, c in enumerate(r):
if c == 0:
drawRectangle(screen, black, bufferX + (b + 1) * 100, bufferY + (a + 1) * 100)
elif c == 1:
drawRectangle(screen, white, bufferX + (b + 1) * 100, bufferY + (a + 1) * 100)
for i in range(len(highlightList)):
if highlightList[i][0] == [int(a), int(b)]:
if highlightList[i][1] == "green":
drawHollowCircle(screen, green, 35, bufferX + (b + 1) * 100 + 50, bufferY + (a + 1) * 100 + 50)
elif highlightList[i][1] == "red":
drawRectangle(screen, red, bufferX + (b + 1) * 100, bufferY + (a + 1) * 100)
elif highlightList[i][1] == "blue":
drawRectangle(screen, blue, bufferX + (b + 1) * 100, bufferY + (a + 1) * 100)
elif highlightList[i][1] == "lightGreen":
drawRectangle(screen, self.lightGreen, bufferX + (b + 1) * 100, bufferY + (a + 1) * 100)
elif highlightList[i][1] == "darkGreen":
drawRectangle(screen, green, bufferX + (b + 1) * 100, bufferY + (a + 1) * 100)
elif highlightList[i][1] == "circle":
drawHollowCircle(screen, gray, 25, bufferX + (b + 1) * 100 + 50, bufferY + (a + 1) * 100 + 50)
elif highlightList[i][1] == "gray":
drawRectangle(screen, gray, bufferX + (b + 1) * 100, bufferY + (a + 1) * 100)
bufferX += 1
bufferY += 5
for x, row in enumerate(board):
for y, val in enumerate(row):
if val != "--":
pieceVal = val.type
color = val.color
if color == "white":
if pieceVal == "Bishop":
screen.blit(self.wB, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Queen":
screen.blit(self.wQ, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "King":
screen.blit(self.wK, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Pawn":
screen.blit(self.wp, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Rook":
screen.blit(self.wR, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Knight":
screen.blit(self.wN, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif color == "black":
if pieceVal == "Bishop":
screen.blit(self.bB, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Queen":
screen.blit(self.bQ, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "King":
screen.blit(self.bK, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Pawn":
screen.blit(self.bp, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Rook":
screen.blit(self.bR, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "Knight":
screen.blit(self.bN, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
"""for piece in pieces:
if piece in val:
pieceVal = val[:2]
if pieceVal == "wB":
screen.blit(wB, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "wQ":
screen.blit(wQ, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "wK":
screen.blit(wK, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "wp":
screen.blit(wp, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "wR":
screen.blit(wR, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "wN":
screen.blit(wN, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "bB":
screen.blit(bB, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "bQ":
screen.blit(bQ, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "bK":
screen.blit(bK, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "bp":
screen.blit(bp, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "bR":
screen.blit(bR, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))
elif pieceVal == "bN":
screen.blit(bN, (bufferX + (y + 1) * 100, bufferY + (x + 1) * 100))"""
s = 150
for a in range(8):
writeText(str(a), screen, s + a * 100, 50)
for b in range(8):
writeText(str(b), screen, 50, s + b * 100)
pygame.display.update()
|
b87a64d959d5e5fbeaa9147d3da41ea2661d0f8b | luckkyzhou/leetcode | /33_1.py | 201 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
if target in nums: return nums.index(target)
else: return -1 |
f6cb8139c7bc123a63ac0e65647d61e32849e5cb | Abi3498/guvi | /lar.py | 174 | 3.53125 | 4 | a=10
b=20
c=30
if(a>b) and (a>c):
great=a
elif(b>a) and (b>c):
great=b
else:
great=c
print ("The greatest number is",great)
|
a5ffaefa1f958326daca4dd3f1a7bdc778f2b59a | jnnersli/BlackJack | /BlackJack/BlackjackModel/Player.py | 1,416 | 3.890625 | 4 | from Card import *
#One of the blackjack players
class Player:
def __init__(self):
self.__hand = []
self.__gameState = "playing" #Keeps players from playing out of turn
def hand(self):
return self.__hand.copy()
def gameState(self):
return self.__gameState
def setGameState(self, state):
self.__gameState = state
#Add a card to the hand
def hit(self, card):
if self.__gameState == "playing":
self.__hand.append(card)
#Sum up the cards in the hand
def countHand(self):
total = 0
aceCount = 0 #Keep a count of the number of aces in the hand
for card in self.__hand:
#The ace has the value of 11...
if card is Card.ACE:
total += 11
aceCount += 1
#Jack, Queen, and King are all worth 10.
elif card is Card.JACK or card is Card.QUEEN or card is Card.KING:
total += 10
else:
total += card.value
#...Unless it is in a hand with a value over 21 in which case it has the value of 1.
while aceCount > 0 and total > 21:
total -= 10
aceCount -= 1
return total
|
014cad9a68bf6b18ab7d860dff49d1e1393137eb | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/primeFactors.py | 401 | 4.25 | 4 | # for 12 -- print 2,2,3
import math
def primeFactors(n):
while n % 2 == 0 and n > 0:
print(2)
n = n // 2
# n becomes odd after above step.
for i in range(3, int(math.sqrt(n) + 1), 2):
while n % i == 0:
print(i)
n = n // i
# until this stage all the composite numbers have been taken care of.
if n > 2:
print(n)
primeFactors(315) |
48886bdd03163e7f7e3142e02978934540562151 | dylean/python-learn | /python从入门到实践/case8.py | 685 | 3.875 | 4 | from collections import OrderedDict
from random import randint
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print name.title() + "'s favorate language is " + \
language.title() + "."
print randint(1, 6)
class Die(object):
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
print randint(1, self.sides)
die1 = Die(6)
for i in range(10):
die1.roll_die()
print '--------------'
die2 = Die(10)
for i in range(10):
die2.roll_die()
|
554b2c63229378225f93730462222cd3180be8d4 | vaibhavranjith/Heraizen_Training | /Assignment1/Q48.py | 166 | 3.796875 | 4 | n=int(input("Enter the number:\n"))
print("Output")
i=3
temp=n
while i>=0:
print(f"{n//(10**i)}*{10**i}={(n//(10**i))*10**i} ")
n=temp%(10**i)
i-=1 |
854b71145d6221a3367b9dcccdfef02b9a8b651d | ezhang-dev/competitive-programming | /DMOJ/Uncategorized/Jason's Theorem.py | 313 | 3.53125 | 4 | def modexp ( g, u, p ):
"""computes s = (g ^ u) mod p
args are base, exponent, modulus
(see Bruce Schneier's book, _Applied Cryptography_ p. 244)"""
s = 1
while u != 0:
if u & 1:
s = (s * g)%p
u >>= 1
g = (g * g)%p;
return s
q=10**9+7
print((pow(2,int(input())+3,q)-5)%q) |
4fe87a1611da3eacdce1ed77161a21395129d7b9 | beOk91/baekjoon2 | /baekjoon10707.py | 215 | 3.59375 | 4 | x=int(input())
y_price=int(input())
y_limit=int(input())
y_price2=int(input())
joi_water_ant=int(input())
print(min(x*joi_water_ant,y_price if y_limit>=joi_water_ant else y_price+ (joi_water_ant-y_limit)*y_price2))
|
99bd7e715f504ce64452c252ac93a026f426554d | gotdang/edabit-exercises | /python/factorial_iterative.py | 414 | 4.375 | 4 | """
Return the Factorial
Create a function that takes an integer and returns
the factorial of that integer. That is, the integer
multiplied by all positive lower integers.
Examples:
factorial(3) ➞ 6
factorial(5) ➞ 120
factorial(13) ➞ 6227020800
Notes:
Assume all inputs are greater than or equal to 0.
"""
def factorial(n):
fact = 1
while n > 1:
fact *= n
n -= 1
return fact
|
18259f93ca893f050a1ce6ca853f2c1e456a503e | aleko-/substitution-cipher-decoder | /decoder.py | 5,860 | 3.671875 | 4 | import re
import random
import json
import sys
import time
if len(sys.argv) < 2:
print "Add the name of the encrypted file and try again"
sys.exit()
elif len(sys.argv) > 2:
print "Too many arguments used. Try again."
sys.exit()
# Read in and preprocess text of the encrypted file
# Store original_decode to remember spacing and returns
original_encrypt = ''
with open(sys.argv[1], 'r') as f:
for line in f:
for char in line:
original_encrypt += char.lower()
original_encrypt = re.sub('[^a-zA-Z\s]+', '', original_encrypt)
to_decode = re.sub('[^a-zA-Z]+', '', original_encrypt)
def collect_quadgrams(string):
"""
Returns a list of all quadgrams in the
input string with their respective frequencies.
"""
tokens = list(string)
tokens_length = len(tokens)
quadgrams = []
first, second, third, fourth = 0, 1, 2, 3
for _ in range(0, tokens_length-3):
quadgram = str(tokens[first]) + str(tokens[second]) + str(tokens[third]) + str(tokens[fourth])
quadgrams.append(quadgram)
first += 1
second += 1
third += 1
fourth += 1
return quadgrams
def put_spaces_back(input_string):
"""
After the text is decoded, this function will apply spaces
and returns to match the formatting of the encrypted text
"""
idx = 0
space_positions = []
# Find positions of spaces and returns in original string
for char in original_encrypt:
if char == " ":
space_positions.append(('space', idx))
elif char == '\n':
space_positions.append(('return', idx))
idx += 1
# Turn string into a list of chars
str_list = []
for char in input_string:
str_list.append(char)
# Insert spaces and returns at the indices noted in space_positions
for pos in space_positions:
if pos[0] == 'space':
str_list.insert(pos[1], ' ')
else:
str_list.insert(pos[1], '\n')
# Turn list back to a string
output = ''
for item in str_list:
output += item
return output
def count(infile):
"""
Creates a dictionary where the keys are alphabetic characters
that occur in the input text and the values are their frequencies.
"""
# Build a string to work with
char_freqs = {}
text = ''
with open(infile, 'r') as f:
for line in f:
for char in line:
text += char.lower()
# Remove non-alphabetic characters
text = re.sub('[\W]+', '', text)
# Construct dictionary of character frequencies
for letter in text:
if letter in char_freqs:
char_freqs[letter] += 1
else:
char_freqs[letter] = 1
return char_freqs
def generate_key(input_dict):
"""
Generates the alphabet in descending
order of the input text's frequency
"""
freq_list = sorted(input_dict.items(), key=lambda x: x[1], reverse=True)
key = ''
for item in freq_list:
key += str(item[0])
# Account for text that doesn't include all 26 letters
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for char in alphabet:
if char not in key:
key += char
return key
def decode(encoded):
"""
Scores a decryption, then swaps two item values in the decode
key, scores the new decryption, and compares the two scores.
The best score is always remembered. This continues until
the best score does not change after 1000 attempts in a row.
"""
# Initialize variables
quadgram_scores = json.load(open('quad_scores.json'))
alphabet = 'etaoinsrhldcumfpgywbvkjxzq' # Descending order of expected frequency in English.
key = generate_key(count(sys.argv[1]))
high_score = float('-Inf')
decode_dict = {}
no_improvement = 0
# Set up seed decryption
for i in range(26):
decode_dict[key[i]] = alphabet[i]
i += 1
# Main loop
while no_improvement < 1000:
decoded = ''
score = 0
# Build decrypted string
for letter in to_decode:
if letter in decode_dict:
decoded += decode_dict[letter]
# Score the current decrypted string
decoded_quadgrams = collect_quadgrams(decoded)
for quadgram in decoded_quadgrams:
if quadgram in quadgram_scores:
score += quadgram_scores[quadgram]
else:
score += (-10.0)
if score > high_score:
high_score = score
best_decode_dict = decode_dict.copy()
best_decode = decoded
no_improvement = 0
else:
no_improvement += 1
# Return to a better key
decode_dict = best_decode_dict.copy()
# Shuffle key
a, b = random.choice(decode_dict.keys()), random.choice(decode_dict.keys())
a_value, b_value = decode_dict[a], decode_dict[b]
decode_dict[a] = b_value
decode_dict[b] = a_value
return high_score, put_spaces_back(best_decode)
def best_decode(iterations):
"""
Runs decode() for specified number of iterations and
returns the decoded text with the highest score. This
function is useful to avoiding getting stuck in a local
optimum that returns the wrong decrypted text.
"""
best = [() for _ in range(iterations)]
for i in range(iterations):
best[i] = decode(to_decode)
print "Iteration #%s \nbest score: %s \nPreview: %s" %(i+1, best[i][0], best[i][1][:100])
print
sort_it = sorted(best, key=lambda x: x[0], reverse=True)
time.sleep(2) # Better on the eyes
print "Decoded text:"
print
return sort_it[0][1]
print "Decoding the text...\n\n", best_decode(2) |
b66ae60a46340a685d0c9e9204f7282c9d02ecc2 | Madhuchigri/Python_work_New | /OOPs_notes_Programs/Polymorphism1.py | 887 | 4.03125 | 4 | # Overriding and Super() Method
class Employee:
def setnumberofworkinghours(self):
self.numberofworkinghours = 40
def display_number_working_hours(self):
print("Number of working hours for an employee:", self.numberofworkinghours)
class Trainee(Employee):
def setnumberofworkinghours(self):
self.numberofworkinghours = 45 # Overriding the value
def resetnumberofworkinghours(self):
super().setnumberofworkinghours() # super method helps in resetting value back
employee = Employee()
employee.setnumberofworkinghours()
employee.display_number_working_hours()
trainee = Trainee()
trainee.setnumberofworkinghours()
trainee.display_number_working_hours()
print("Number of working hours of a trainee after the reset:", end = '')
trainee.resetnumberofworkinghours()
trainee.display_number_working_hours()
|
a0e220589d9e1535653a925f5117bdfaed2ccab2 | alimoreno/TIC-2-BACH | /PYTHON/parimpareador.py | 348 | 4.03125 | 4 | def parimpareador():
x=input("Dime un numero ")
y=input("Dime otro numero ")
if(x%2>0 and y%2>0):
print "Los dos numeros son impares"
if((x%2==0 and y%2>0) or (x%2>0 and y%2==0)):
print "Un numero es par y el otro impar"
if(x%2==0 and y%2==0):
print "Los dos numeros son pares"
parimpareador()
|
dcf9564c7dc03e120309ad0b60548804af2c6d30 | mucheniski/python-for-data-science | /module2/QuesitionsReview.py | 108 | 3.734375 | 4 | A=('a','b','c')
print(A[0])
Dict={"A":1,"B":"2","C":[3,3,3],"D":(4,4,4),'E':5,'F':6}
print(Dict["D"]) |
01a24ae55c6319c043829e890631432e04c0acec | edumaximo2007/Mundo1 | /Desafio23.py | 840 | 4.0625 | 4 | print('-=-'*10)
print('''\033[7m DESAFIO 23 \033[m''')
print('-=-'*10)
print('')
print('''\033[1mFaça um programa que leia um número de 0 a 9999 e mostre na tela cada um digitos separados.
EX:
Digite um número: 1834
Unidade: 4
Dezena: 3
Centena: 8
Milhar: 1\033[m''')
print('')
p1 = str(input('Podemos começar? '))
if p1 =='Sim':
print('Responda abaixo')
else:
print('Você não tem escolha inseto maldito')
print('')
n1 = int(input('Digite um número: '))
print('Analisando o número: {}'.format(n1))
u = n1 // 1 % 10
d = n1 // 10 % 10
c = n1 // 100 % 10
m = n1 //1000 % 10
print('Unidade: {}'.format(u))
print('Dezena: {}'.format(d))
print('Centena: {}'.format(c))
print('Milhar: {}'.format(m))
print('')
print('\033[1mParabéns você concluiu esta tarefa com exito!\033[m') |
1173b05664e2ea8cf6382f8dc3a61e8e224d63cf | liamphmurphy/2020_hackathon | /src/beers.py | 1,509 | 4.03125 | 4 | class Beers:
all_beers = {
# values are as follows: drink name, attributes, acceptable locations, cost to make, purchase price
"Fresh Squeeze": ("Fruity", "Hoppy", ["Ashland", "Portland"], 2.50, 4.00),
"Kombucha": ("Non-Alcoholic", "Flavorful", ["Ashland", "Portland"], 3.00, 4.25),
"White Claw": ("Non-Alcoholic", "Flavorful", ["Medford", "Portland", "Mt Shasta"], 2.00, 3.25),
"Amber Ale": ("Smooth", "Sweet", ["Ashland", "Portland"], 3.25, 4.10),
"Drop Top": ("Smooth", "Sweet", ["Medford", "Mt Shasta"], 2.75, 3.50),
"Alpha Centauri": ("Fruity", "Hoppy", ["Medford", "Mt Shasta"], 3.50, 4.25)
}
def get_beer(self, name):
return self.all_beers[name]
def get_all_beers(self):
return self.all_beers
# print_beer takes in the name of the beer (key in the dict) and prints it
def _print_beer(self, beer_key):
print("{0}".format(beer_key))
print("\tAttributes: {0}, {1}".format(self.all_beers[beer_key][0], self.all_beers[beer_key][1]))
print("\tAcceptable Locations: {0}".format(self.all_beers[beer_key][2]))
print("\tCost to Produce: ${0:.2f}".format(self.all_beers[beer_key][3]))
print("\tPurchase Price: ${0:.2f}".format(self.all_beers[beer_key][4]))
# prints all of the beers
def print_all_beers(self):
# iterate through the dictionary and print all of the beers
for beer in self.all_beers:
self._print_beer(beer)
|
f942789a43fbc4158b3260f70ea9e82271fbe870 | carlox7/Intro-to-computer-science-with-python | /lecture4.py | 606 | 3.84375 | 4 | ##def withinEpsilon(x, y, epsilon):
## return abs(x - y) <= epsilon
##
##print(withinEpsilon(2,3,1))
##val = withinEpsilon(2,3,0.5)
##print(val)
##
##def f(x):
## x = x + 1
## print('x', x)
## return x
##x = 3
##z = f(x)
##print('z = ', z)
##print('x = ', x)
##
##def f1(x):
## def g():
## x = 'abc'
## assert false
##for i in range(10):
## print(i + 1)
tupleOfNumbers = (3.14159, 2, 1, -100, 100, 240)
tupleOfStrings = ('What', 'is', 'my', 'name?')
print(tupleOfNumbers[1 : 3])
print(tupleOfStrings[0 : 3])
##single value tuple needs a comma
onesie = (50,)
print(onesie)
|
d735fa704efc96cb8e00fdd1b984f76d5410c134 | rishabhsharma015/python_programs | /alphabeticalorderstr.py | 132 | 4.03125 | 4 | n=input("Enter the String: ")
k=list(n)
k.sort(reverse=False)
s=''.join(map(str,k))
print("String characters in sorted order: ",s)
|
3b55d3ba70c7145c34f54050baa1b6767e1fbf1b | clovery410/mycode | /leetcode/242valid_anagram.py | 502 | 3.578125 | 4 | class Solution(object):
def isAnagram(self, s, t):
char_list = [0 for x in xrange(26)]
for item in s:
char_list[ord(item) - ord('a')] += 1
for item in t:
char_list[ord(item) - ord('a')] -= 1
is_anagram = True
for i in xrange(26):
if char_list[i] != 0:
is_anagram = False
return is_anagram
if __name__ == '__main__':
sol = Solution()
s = "rat"
t = "tar"
print sol.isAnagram(s, t)
|
40845e61d51b2ca3b31540a7c2b10a2fe1827894 | cyrilvincent/math | /demo_tuple.py | 259 | 3.765625 | 4 | from typing import List, Tuple, Iterable
def my_function(param: float) -> Tuple[int, str]:
return 1, "toto"
def sum(l: List[float]):
res = 0
for x in l:
res += x
return res
x, y = my_function(3.14)
print(x, y)
print(sum([1,2,3]))
|
b863c57cc46fcb0220334be7400e3295f39c6380 | SourTofu/Python-learning | /week1/边长为N的正方形.py | 98 | 3.828125 | 4 | while True:
number = int(input('>>>'))
for i in range(number):
print(number*"*\t") |
5206f684b1bfdbe1fcbb18994df1eedf6057bcb7 | LarmIg/Algoritmos-Python | /Capitulo 3/Exercicio O.py | 514 | 4 | 4 | # Elaborar um programa que leia quatro valores numéricos inteiros (variáveis A, B, C e D). Ao final o programa deve apresentar o resultado do produto (variável P) do primeiro com o terceiro valor, e o resultado da soma (variável S) do segundo com o quarto valor.
A = int(input('Informe o valor de A:'))
B = int(input('Informe o valor de B:'))
C = int(input('Informe o valor de C:'))
D = int(input('Informe o valor de D:'))
P = A + C
S= B + D
print('Valor de P é {} e o Valor de S é {}'.format(P, S)) |
35625d25a698a3a9bbc4cbfb78f51d51bd6acdf7 | andrewwebukha/pythonbasic | /string_operations.py | 879 | 4.375 | 4 | #concatenation using a plus operator, using .format
first_name = "Andrew"
last_name = "Webukha"
#full_name ="{} {}".format(first_name,last_name)
#print(full_name)
print("The tallest person in the family of {} is named after {}".format(last_name,first_name))
#full_name= first_name+" "+last_name
#print(full_name)
name= "John Juma"
name2= "kevin kirimi"
name3= "FABIAN KEN"
print (name.capitalize())
print(name2.title())
sen= "man is to error because man did not create man"
print(sen.count("man"))
print(sen.count(" "))
print(sen.count("e"))
#python is case sensitive
#string slicing
#in slicing left of the colon signifies the starting element. right of the colon signifies the ending position but the end element is excluded
print(sen[0])
print(sen[-1])
print(sen[0:2])
print (sen.__len__())
jina= "muyani"
print(jina[1:2])
print(jina[::-1])
#print(jina[5:3:-1])
#split
print(sen.split()) |
1ad3a2ea0c11fa8f921430fd4896349f94e5d580 | xc1111/untitled2 | /hk_homework1_10/demo1.py | 1,000 | 4 | 4 | # 定义猫类
class Cat:
# 构造函数初始化:初始化同时设置初始值姓名和颜色
def __init__(self,name,color):
# 形参姓名保存为属性
self.name=name
# 形参颜色保存为属性
self.color=color
# 定义捕捉方法
def catch(self):
# 打印
print(f"抓到老鼠了")
# 定义str方法:当输出对象时可不输出地址而是自定义的内容
def __str__(self):
# return "我的名字叫 %s 颜色是 %s " % (self.name, self.color)
# 返回打印内容
return print(f"我的名字叫{self.name},我肤色是{self.color}")
# return print ('my name is {}, color is {}'.format(self.name,self.color))
# 类模板创建对象 第一只猫,传入名字和颜色的实参
onecat=Cat("黑猫","黑色")
# 调用对象捕捉方法
onecat.catch()
# 打印对象 第一只猫
print(onecat)
# 就是打印结果可正常显示但还会报错不知道何原因,如何改??? |
29cd9dda629eadf5ee65fc94105cb8867b3bb11c | KamarajuKusumanchi/rutils | /python3/get_urls.py | 986 | 3.625 | 4 | #! /usr/bin/env python3
# Script to get urls in a url.
import argparse
import requests
from bs4 import BeautifulSoup
import re
def create_parser():
parser = argparse.ArgumentParser(
description='Get urls in a url'
)
parser.add_argument(
'-v', '--verbose', action='store_true',
default=False, dest='verbose',
help='explain what is being done'
)
parser.add_argument(
'url', action='store',
help='source url'
)
return parser
def get_urls(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
urls = [
x.get('href')
for x in soup.find_all(name='a', attrs={'href': re.compile('^https*://')})
]
return urls
if __name__ == '__main__':
# src = sys.argv[1]
parser = create_parser()
args = parser.parse_args()
if args.verbose:
print(args)
url = args.url
urls = get_urls(url)
for x in urls:
print(x)
|
efc3e0f87062b466b6cfa04b841a001f74e25717 | hardhary/PythonByExample | /Challenge_058.py | 644 | 4.25 | 4 | #058 Make a maths quiz that asks five questions by randomly generating two whole numbers to make
#the question (e.g. [num1] + [num2]). Ask the user to enter the answer. If they get it right add
#a point to their score. At the end of the quiz, tell them how many they got correct out of five.
import random
def maths():
score = 0
for i in range(1,6):
num1 = random.randint(1,50)
num2 = random.randint(1,50)
correct = num1 + num2
print (num1, "+", num2, "=")
answer = int(input("Your answer: "))
print()
if answer == correct:
score = score + 1
print("Your scored {} out of 5".format(score))
maths()
|
9a1d4f2fead15f720ea4f0cacc551926cc8b2dde | CamilliCerutti/Python-exercicios | /Curso em Video/ex082.PY | 704 | 4.0625 | 4 | # DIVIDINDO VALORS EM VARIAS LISTAS
# Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.
valores = list()
impar = list()
par = list()
while True:
num = int(input('Digite um valor: '))
if num % 2 == 0:
par.append(num)
elif num % 2 != 0:
impar.append(num)
valores.append(num)
resp = input('Quer continuar? [S/N]: ').upper()
if 'N' in resp:
break
print(f'A lista completa é: {valores}\nOs valores pares são: {par}\nOs valores impares são: {impar}') |
2f7baa0cdeb7a324dd5b1f076315ef4bc34b680b | Aasthaengg/IBMdataset | /Python_codes/p03547/s006743911.py | 98 | 3.734375 | 4 | s = list(input())
if s[0] == s[2]:
print("=")
elif s[0] < s[2]:
print("<")
else:
print(">") |
30336b1bffa8a40ba70efeff58ffee90e7d339be | sagarnikam123/learnNPractice | /hackerEarth/practice/dataStructures/arrays/1D/fredoAndLargeNumbers.py | 3,134 | 3.578125 | 4 | # Fredo and Large Numbers
#######################################################################################################################
#
# Fredo is pretty good at dealing large numbers. So, once his friend Zeus gave him an array of N numbers,
# followed by Q queries which he has to answer. In each query , he defines the type of the query and the number f
# for which Fredo has to answer. Each query is of the following two types:
# Type 0: For this query, Fredo has to answer the first number in the array (starting from index 0) such that its
# frequency is atleast equal to f.
# Type 1: For this query, Fredo has to answer the first number in the array such that frequecy is exactly equal to f.
# Now, Fredo answers all his queries but now Zeus imagines how he should verify them .
# So, he asks you to write a code for the same.
# Note: If there is no number which is the answer to the query, output 0.
# Use fast I/O.
#
# Input :
# The first line of the input contains N , the size of the array
# The next line contains N space separated integers.
# The next line contains Q, denoting the number of queries.
# Then follow Q lines, each line having two integers type and f,
# denoting the type of query and the frequency for which you have to answer the query.
#
# Output:
# You have to print the answer for each query in a separate line.
#
# Input Constraints:
# 1 <= N <= 106
# 1 <= A[i] <= 1018
# 1 <= Q <= 106
# 0 <= type <= 1
# 1 <= f <= 1018
#
# SAMPLE INPUT
# 6
# 1 2 2 1 2 3
# 5
# 0 1
# 0 2
# 1 2
# 1 3
# 0 3
#
# SAMPLE OUTPUT
# 1
# 1
# 1
# 2
# 2
#
# Explanation
# Query 1: 1 is the first number from left with frequency atleast 1.
# Query 2: 1 is the first number from left with frequency atleast 2.
# Query 3: 1 is the first number from left with frequency exactly 2.
# Query 4: 2 is the first number from left with frequency exactly 3.
# Query 5: 2 is the first number from left with frequency atleast 3.
#
#######################################################################################################################
mathura = int(input().strip())
chinnaMasti = input().strip().split(' ')
chatniKela = int(input().strip())
#complexKartavya
radhikaChiwada = [int(i) for i in chinnaMasti] # toInt
rangaSatta = set(radhikaChiwada) #unique
groupStudy = [] #containFrequency
#calculateFrequency
for zebraFish in rangaSatta :
goldenRatio = 0
for piche in radhikaChiwada :
if zebraFish == piche :
goldenRatio += 1
groupStudy.append(goldenRatio)
#print(rangaSatta)
#print(groupStudy)
for blueTris in range(chatniKela):
gangaVan = [int(z) for z in input().strip().split(' ')]
if gangaVan[0] == 0: #atleastFrequency
for pittu in range(len(groupStudy)):
if groupStudy[pittu] >= gangaVan[1]:
print(radhikaChiwada[pittu])
break
else: #exactlyFrequency
for chittu in range(len(groupStudy)):
if groupStudy[chittu] == gangaVan[1]:
print(radhikaChiwada[chittu])
break
|
045482fcfb5e250049bf7facce519a2cbb6dc0a9 | shreya3079/guess-the-number | /guess the number.py | 913 | 3.984375 | 4 | import random
process = True
no = random.randint(0, 100)
chance = 0
print("Enter a number between 0 to 100\n")
print("You have only 5 chances to guess the number\n")
while process:
choice = input("Guess the number:")
if int(choice) == no:
print("Yeah!!! You guessed the number!!!")
print("Would you like to play it again?", "\n 1. Yes \n 2. No")
option = input()
if option == str(1):
chance = 0
pass
if option == str(2):
exit("Thanks for playing!!! See you again")
elif int(choice) > no:
print("Number is too high")
chance = chance + 1
elif int(choice) < no:
print("Number is too low")
chance = chance + 1
else:
continue
if int(chance) == 5:
print("You have reached the limit")
print("The number was ", no)
exit() |
03792ec4b03098ca2248e50df1f90d3ba50dd4cb | rhanugr/webautomationusingpyhton | /pythonProject/APITesting/Basics/Basictest.py | 163 | 4.125 | 4 | # TYPE CASTING
# Converting Integer to String and String to Integer
age = input("Enter your Age : -")
age = int(age)+5
print("Age of the Man is :- " + str(age)) |
f3bcddb0e40ce21e84362daef59a33309384a230 | brandon-rowe/Python | /Py Programs/MyPy/Beginner/Worms/exploitFile.py | 585 | 3.640625 | 4 | def main():
inp = input("Please enter your file name with extension. ")
read(inp)
def read(inp):
myFile = open(inp,'r')
data = myFile.read()
words = data.split(" ")
print()
print(data)
print(words)
i = 1
while i > 0:
i += 1
m = 1
fname = "Kronus"
lname = ".txt"
mInit = i
fullName = fname+str(mInit)+lname
outFile = open(fullName, 'w')
outFile.write(data)
print()
print(data)
print()
m += 1
outFile.close()
#def write(data):
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.