blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
70d935319fcb560475b7fe4cc1b772e5df53cf77 | Herebert1706/Practicas-de-Estructura-de-Datos | /Recursividad.py | 442 | 3.78125 | 4 | def naturales(x): //Aqui estoy definiendo una funcion en donde utilizare la variable x
if x<101: //Hago un if en donde le doy la condicion que x sea menor que 100
print(x) //Mando a imprimir los numeros
x=x+1 //Aqui incremento el numero de 1 en 1
return naturales(x) //Regreso la funcion de donde va empezar la suma
print(naturales(1)) //Imprimo los primeros 100 numeros naturales a partir del 1 hasta el 100
|
a88a7974a6c84f1fb9838ad0ef2fe2ee2705563f | yymin1022/CAU-Computational-Thinking-and-Problem-Solving-Assignment1 | /문제6.py | 1,409 | 3.59375 | 4 | import random
player1 = str(input('1 플레이어의 이름은? '))
player2 = str(input('2 플레이어의 이름은? '))
# 현재 진행중인 라운드
round = 1
# 두 플레이어의 위치를 출발지점(0)으로 초기화
current1 = 0
current2 = 0
while current1<30 and current2<30:
# 플레이어의 주사위 값
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
# 각 플레이어의 현재 위치에 주사위 값을 더함
current1 += dice1
current2 += dice2
print(player1, '은(는)', dice1, '가 나왔습니다. 현재위치', current1)
print(player2, '은(는)', dice2, '가 나왔습니다. 현재위치', current2)
if current1>=30 and current2<30: # 1 플레이어만 30 이후의 위치에 도달한 경우
print(round, '라운드만에', player1, '이(가) 이겼습니다.')
break
elif current1<30 and current2>=30: # 2 플레이어만 30 이후의 위치에 도달한 경우
print(round, '라운드만에', player2, '이(가) 이겼습니다.')
break
elif current1>=30 and current2>=30: # 두 플레이어가 동시에 30 이후의 위치에 도달한 경우
print(round, '라운드만에 무승부로 게임이 종료되었습니다.')
break
# 게임이 종료되지 않은 경우 현재 라운드에 1을 더하고 반복문 다시 실행
round += 1 |
d2ee40453faed04f6e08bacf0862fe762daca518 | amarnadhreddymuvva/pythoncode | /armstrong.py | 199 | 4.03125 | 4 | num=int(input("eneter a number"))
sum=0
temp=num
while(temp>0):
digit=temp%10
sum=sum+digit**3
temp=temp//10
if (num==sum):
print(("armstrong number"))
else:
print("not")
|
7513fc5f2fb44654ffa11d470903ad6f61dec95a | fritzreece/euler-solns | /Problem24/permute.py | 601 | 3.765625 | 4 | from math import ceil
def factorial(n):
res = 1
while n > 0:
res *= n
n -= 1
return res
# assume perms are zero indexed
def nth_perm(string, n):
string = "".join(sorted(string))
if n == 0:
return string
# the index in the sorted string of the character that will be first in the permutation
subfac = factorial(len(string)-1) # only calc once
# current position of character that will be in the front
pos = n // subfac
subperm_num = n % subfac
sub = nth_perm(string[:pos] + string[pos+1:], n % subfac)
return string[pos] + sub
|
c70d4fbcdf636d8dba4c3fc81e33ebe27ac533e1 | AlessandroFMello/EstruturaDeRepeticao | /Exercício014.py | 723 | 3.703125 | 4 | import msvcrt
while True:
arr = []
arrP = []
arrI = []
contador = 0
arr.append(int(input('Digite um número:\n')))
while contador < 9:
arr.append(int(input('Digite outro número:\n')))
contador += 1
for x in arr:
if x % 2 == 0:
arrP.append(x)
elif x % 2 != 0:
arrI.append(x)
print('Você escolheu os números:\n%s\n' % arr)
print('Os pares são %s, logo temos %s pares\n' % (arrP, len(arrP)))
print('Os ímpares são %s, logo temos %s ímpares' % (arrI, len(arrI)))
print('\nPressione qualquer tecla para repetir ou pressione 1 para sair')
key = msvcrt.getch()
if key == b'1':
break
|
37313952d959a583da36c0b839ddd39f60651416 | rduvvi/MyPythonWorks | /Operators.py | 1,149 | 4.21875 | 4 | # Python operators used to perform operation on operands.
# Arithmetic Operators * ,/,-
x=4
y=5
print(x+y)
# Comparison Operators Likewise,you can try (x < y, x==y, x!=y, etc.)
print(('x > y is',x>y))
num1=5
num2=6
res = num1 + num2
res += num1
print(("Line 1 - Result of + is ", res))
# Logical Operators - AND,NOT,OR
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
# Membership Operators - in, not in
x=4
y=5
list=[1,2,3,4,5];
if(x in list):
print("x in the given list")
else:
print("x not availble in the given list")
if(y not in list):
print("Y is not available in the list")
else:
print("Y in the given list")
# Identity Operators - To compare the memory location of two objects, Identity Operators are used. The two identify operators used in Python are (is, is not).
x=20
y=20
if(x is y):
print("x & Y SAME identity")
else:
print("x & y have DIFFERENT identity")
# Operator precedence - The operator precedence determines which operators need to be evaluated first.
v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;
print("Value of (v+w) * x/ y is ", z) |
48a1d2b0e77eb550a32dfb1f21dad375c9d8a834 | kavya199922/python_tuts | /Day-3/py_json.py | 927 | 3.859375 | 4 | #loading json data from file
#serialization:json=>python dict
#read data (json) from a file:
# convert:python(dict)
import json
with open('dat_json.json','r') as f:
data=json.load(f)
print((data))
str1='''
{
"23": {
"name": "Jonas",
"email": "[email protected]",
"role": "manager"
},
"47": {
"name": "Martha",
"email": "[email protected]",
"role": "Team Lead"
}
}
'''
# print((json.loads(str1)))
# #deserialization:python->JSON
#
#
person_dict = {
'name': 'Bob',
'age': 12,
'children': None,
'ismarried':False
}
person_json = json.dumps(person_dict)
# Output: {"name": "Bob", "age": 12, "children": null}
print((person_json))
#write to a file
person_dict = {
"name": "Bob",
"languages": ["English", "Fench"],
"married": True,
"age": 45
}
with open('person1.json', 'w') as json_file:
json.dump(person_dict, json_file) |
e1b2c1ab3b48a9b14b49f12fd0b9fcc890d5307d | aprilxyc/coding-interview-practice | /leetcode-problems/1213-intersection-of-two-arrays.py | 1,866 | 3.90625 | 4 | class Solution:
def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
# O(N) where N is the length of the longest array
# O(N) space where N is the length of the longest array
# keep pointers on all 3 arrays
num1 = num2 = num3 = 0
final_list = []
while num1 < len(arr1) and num2 < len(arr2) and num3 < len(arr3):
p1 = arr1[num1]
p2 = arr2[num2]
p3 = arr3[num3]
# if they are all the same number, then add them to final list
if p1 == p2 == p3:
final_list.append(p1) # append either of them, it doesn't matter
num1 += 1
num2 += 1
num3 += 1
continue
max_number = max(p1, p2, p3)
if p1 < max_number:
num1 += 1
if p2 < max_number:
num2 += 1
if p3 < max_number:
num3 += 1
return final_list
# can do this using python functions such as set and sorted:
def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
return sorted(set(arr1) & set(arr2) & set(arr3))
# remember another method is you can also sort it and use pointers to find the common elements
# my most recent solution (11/01) ^ improved so much from the above lol
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
common_table = {} # holds the items in the first list
result = [] # returns the final output
for i in nums1: # go through the first list
common_table[i] = 0 # put all its elements into the hash table
for j in nums2:
if j in common_table:
result.append(j)
return set(result) |
8390b5fa589a2464e80224c346a4c774055301bb | MarijnJABoer/AwesomePythonFeatures_Marvel | /marvel_universe.py | 3,962 | 3.703125 | 4 | class MarvelCharacter:
"""
Creates a character from the Marvel universe
"""
# class atribute
location = "Earth"
def __init__(self, name: str, birthyear: int, sex: str):
self._name = name
self.birthyear = birthyear
self.sex = sex
def __repr__(self):
return f"{self.__class__.__name__}({self._name}, birthyear: {self.birthyear})"
def says(self, words):
return f"{self._name} says {words}"
@staticmethod
def StanLee():
return MarvelCharacter("Stan Lee", 1922, "Male")
class Hero(MarvelCharacter):
"""
Create a Marvel hero
"""
def __init__(self, name: str, birthyear: int, sex: str, species: str, alias: str, weapon: tuple = None):
super().__init__(name, birthyear, sex)
self.species = species
self.alias = alias
if weapon is not None:
self.weapon_name, self.weapon_type = weapon
self._current_affilitions = {
"Asgardian Royal Family": True,
"Avengers": True,
"Revengers": False}
def __repr__(self):
return f"{self.__class__.__name__}({self._name}, birthyear: {self.birthyear}, alias: {self.alias})"
@staticmethod
def fight_outcome(fight):
"""
Determine if the Hero won fights as an Avengers
"""
fights = {
"Ebony Maw": True,
"Cull Obsidian": True,
"Ultron": True,
"Proxima Midnight": True,
"Thanos": False}
return fights.get(fight, False)
@classmethod
def spider_man(cls):
return cls("Peter Benjamin Parker", 2001, "Male", "Human", "Spider-Man", ("Web-Shooters", "Mechanical Device"))
@classmethod
def iron_man(cls):
return cls("Anthony Edward Stark", 1970, "Male", "Human", "Iron-Man", ("Arc Reactor", "Power source"))
@classmethod
def hulk(cls):
return cls("Robert Bruce Banner", 1969, "Male", "Human", "The Incredible Hulk", ("Stretchable Pants", "Clothing"))
class Villain(MarvelCharacter):
"""
Creates a Marvel villain
"""
def __init__(self, name: str, birthyear: int, sex: str, species: str, villain_to: str, affiliation: str = None):
super().__init__(name, birthyear, sex)
self.species = species
self.villain_to = villain_to
if affiliation is not None:
self.affiliation = affiliation
def __repr__(self):
return f"{self.__class__.__name__}({self._name}, birthyear: {self.birthyear}, villain to: {self.villain_to})"
@classmethod
def ultron(cls):
return cls("Ultron", 2015, "Male", "Android", "Avengers", None)
@classmethod
def whiplash(cls):
return cls("Ivan Antonovich Vanko", 1968, "Male", "Human", "Iron Man", "Hammer Industries")
class MinorCharacter(MarvelCharacter):
"""
Creates a Marvel minor character
"""
def __init__(self, name: str, birthyear: int, sex: str, species: str, related_to: str = None):
super().__init__(name, birthyear, sex)
self.species = species
if related_to is not None:
self.related_to = related_to
def __repr__(self):
return f"{self.__class__.__name__}({self._name}, birthyear: {self.birthyear}, related to: {self.related_to})"
if __name__ is "__main__":
iron_man = MarvelCharacter("Anthony Edward Stark", 1970, "Male")
print("Iron man: ", iron_man)
spider_man = Hero(name="Peter Benjamin Parker", birthyear=2001, sex="Male",
species="Human", alias="Spider-Man", weapon=("Web-Shooters", "Mechanical Device"))
print("Spiderman: ", spider_man)
stan_lee = spider_man.StanLee()
print("Stan Lee: ", stan_lee)
ultron = Villain.ultron()
print("Ultron: ", ultron)
whiplash = Villain.whiplash()
print("Whiplash: ", whiplash)
spider_man = Hero.spider_man()
print("Spiderman: ", spider_man)
iron_man = Hero.iron_man()
print("Iron man: ", iron_man)
hulk = Hero.hulk()
print("Hulk: ", hulk)
|
624b07553a025dd27f0071708a0900b13885104a | katiakata1/Codewars_python | /detect_pangram.py | 742 | 4.0625 | 4 | #A pangram is a sentence that contains every single letter of the alphabet at
#least once. For example, the sentence "The quick brown fox jumps over the
#lazy dog" is a pangram, because it uses the letters A-Z at least once
#(case is irrelevant).
#Given a string, detect whether or not it is a pangram. Return True if it is,
#False if not. Ignore numbers and punctuation.
import string
def is_pangram(s):
sentence = s.lower()
listing = ""
for letter in string.ascii_letters:
for i in range(len(sentence)):
if letter == sentence[i] and letter not in listing:
listing += letter
print(listing)
if listing == string.ascii_lowercase:
return True
else:
return False |
4bce2b3fa1ebe1d3715bd892351acf7f4e4eae14 | syw2014/DL-Course | /course/cs231n/assignment1/classifier/linear_svm.py | 4,704 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : Jerry.Shi
# File : linear_svm.py
# PythonVersion: python3.5
# Date : 2017/4/13 9:08
# Software: PyCharm Community Edition
import numpy as np
from random import shuffle
def svm_loss_naive(W, X, y, reg):
"""
A simple implementation of Structured SVM loss function
:param W: C X D array of weights, C is the number of class, D is the number of sample dimension
:param X: D X N array of data, data
:param y: 1-dimension array of class labels, the size of array is N number of class labels from 0,...,k-1
:param reg: regularization , type float
:return: a tuple of loss and dW, the shape is as the same of W
"""
# step 1, weight initialize the gradient value to 0
dW = np.zeros(W.shape)
# step 2, get class number and sample number
num_classes = W.shape[0]
num_train = X.shape[1]
loss = 0.0
# step 3, compute loss and the gradient
# traverse train samples
for i in range(num_train):
scores = W.dot(X[:, i]) # compute similarity of sample and all classes
correct_class_score = scores[y[i]]
# compute margin and gradient
for j in range(num_classes):
if j == y[i]:
continue
margin = scores[j] - correct_class_score + 1 # note delta = 1
if margin > 0:
loss += margin
# compute gradient
# Note: not full understand !!!!
dW[y[i], :] -= X[:, i].T # compute the correct class gradient
dW[j, :] += X[:, i].T # sum each contribution of X_i
# step 4, process the loss
# Right now loss is the sum over all training sampels, but we want it to be an average instead so we divided by
# num_train
loss /= num_train
# step 5
# add regularization
loss += 0.5 * reg * np.sum(W * W)
# step 6, process gradient
dW /= num_train
# step 7, Gradient regularization that carries through per https://piazza.com/class/i37qi08h43qfv?cid=118
dW += reg * W
return loss, dW
def svm_loss_vectorized(W, X, y, reg):
"""
Structured SVM loss, vectorized implementation
:param W: C X D array of weights, C is the number of class, D is the number of sample dimension
:param X: D X N array of data, data
:param y: 1-dimension array of class labels, the size of array is N number of class labels from 0,...,k-1
:param reg: regularization , type float
:return: a tuple of loss and dW, the shape is as the same of W
"""
# step 1, create store variable
# store the training loss in variable loss
loss = 0.0
dW = np.zeros(W.shape) # gradient matrix
# step 2, get use info for model
D = X.shape[0] # sample dimension
num_classes = W.shape[0] # number of class labels
num_train = X.shape[1] # number of train sample
# step 3, compute score of weight * trainning data
scores = W.dot(X)
# step 4, Construct correct_scores vecto
# Construct correct_scores vector that is D x 1-dimension (or 1xD) so we can subtract out
# where we append the "true" scores: [W*X]_{y_1, 1}, [W*X]_{y_2, 2}, ..., [W*X]_{y_D, D}
# Using advanced indexing into scores: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
# Slow, sadly:
# correct_scores = np.diag(scores[y,:])
# Fast (index in both directions):
correct_scores = scores[y, np.arange(num_train)] # using the fact that all elements in y are < C == num_classes
# step 5, compute margin
mat = scores - correct_scores + 1 # delta = 1
mat[y, np.arange(num_train)] = 0 # accounting for the j=y_i term we shouldn't count (subtracting 1 makes up for it since w_j = w_{y_j} in this case)
# step 6, compute maximum
thresh = np.maximum(np.zeros((num_classes, num_train)), mat)
# step 7, compute training loss
loss = np.sum(thresh)
loss /= num_train
# step 8, add regularization
loss += 0.5 * reg * np.sum(W * W)
# step 9, compute gradient over vectorized
# Binarize into integers
binary = thresh
binary[thresh > 0] = 1
# Perform the two operations simultaneously
# (1) for all j: dW[j,:] = sum_{i, j produces positive margin with i} X[:,i].T
# (2) for all i: dW[y[i],:] = sum_{j != y_i, j produces positive margin with i} -X[:,i].T
col_sum = np.sum(binary, axis=0)
binary[y, range(num_train)] = -col_sum[range(num_train)]
dW = np.dot(binary, X.T)
# Divide
dW /= num_train
# Regularize
dW += reg * W
return loss, dW
|
d0c6ce4565c351df61c091e9f4fc4e7be2f0b946 | jogusuvarna/jala_technologies | /polymorphism.py | 426 | 4.0625 | 4 | '''Runtime Polymorphism with Data Members/Instance variables, Repeat the above
process only for data members.'''
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def __add__(self, other):
m1=self.m1+other.m1
m2 = self.m2 + other.m2
s=Student(m1,m2)
return s
student1=Student(55,85)
student2=Student(85,85)
s=student1+student2
print(s.m1)
print(s.m2)
|
0af3c7f157a30bd9bda21fbc5fa9ca56bd2c634e | nishathapa/CB | /Day2/loop.py | 195 | 3.640625 | 4 | line = input("Enter your fav line")
letters = {}
for ch in line:
if ch in letters:
letters[ch]=letters[ch] + 1
else:
letters[ch]= 1
print(letters)
# print(letters["a"]) |
2e09c4f0904a5e47f4b1f0282204b7de207fc547 | wang550564900/pythoncode | /py_homework/day4homework.py | 4,123 | 4 | 4 | # class Father(): #声明父类
# def __init__(self,a,b):#给类设置属性
# self.a=a
# self.b=b
# #方法一
# def add(self):# 类的方法add
# return self.a+self.b
# #方法二
# def sub(self):
# return self.a - self.b
# class Son(Father):#声明子类继承父类
# def print_add(self):
# #调用父类的方法
# print(self.add())
# #重写父类的方法
# def sub(self):
# #调用父类的属性
# return self.a*2-self.b
# son=Son(6,3)
# son.sub()
# son.add()
# 类的属性和方法练习:
# 写一个学生类
# 写出学生应该有的属性和方法
# class Student():
# def __init__(self,name,age,sid,hobby):
# self.name=name
# self.age=age
# self.sid=sid
# self.hobby=hobby
# def study(self):
# print("%s同学是个优秀的学习委员他今年%d学号是%d他的爱好是%s"%(self.name,self.age,self.sid,self.hobby))
# s1 = Student("小强",18,101,"学习")
# s1.study()
# 2. 继承
# 写一个人类类
# 再写一个学生类
# 学生类继承人类的属性和方法
# class Person():
# def __init__(self,name,age):
# self.name=name
# self.age=age
# def func(self):
# return "%s今年%d喜欢插花" % (self.name,self.age)
# def work(self,work):
# return "他的工作是%s" % (work)
# p=Person("张三",18)
# x=p.work("测试")
# print(x)
# class Student(Person):
# def __init__(self,name,age,con):
# Person.__init__(self,name,age)
# self.con=con
# def print_func(self):
# x=self.func()
# print(x)
# def sfunc(self,name,age):
# return "%s今年%d班里一支花"%(name,age)
#
# s=Student("小红",18,"五班")
# #s.print_func()
# s1=s.sfunc("小黄",22)
# print(s1)
#3. 定义一个字典类:dictclass。完成下面的功能:
# dict = dictclass({你需要操作的字典对象})
# 1 删除某个key,并返回删除后的字典
# del_dict(key)
# 2 判断某个键是否在字典里,如果在返回键对应的值,不存在则返回"not found"
# get_dict(key)
# 3 返回键组成的列表:返回类型;(list)
# get_key()
# 4 合并字典,并且返回合并后字典的values组成的列表。返回类型:(list)
# update_dict({要合并的字典})
#创建一字典类
# class Dictclass():
# #设置类的属性(这里的属性是一个字典)
# def __init__(self,dict):
# self.dict=dict
# #定义删除key的方法如果调用这个函数需要传一个字典(实例化类需要一个字典)和一个key进来
# def del_dict(self,key):
# #如果传进来的key在字典里面
# if key in self.dict.keys():#kyes()以列表返回一个字典所有的键
# #删除这个键对应的值
# del self.dict[key]
# #返回删除后的字典
# return self.dict
# else:
# #如果字典里没有对应的key则返回这句话
# return "this dict don't have this key"
# #获取键对应的字典的方法
# def get_dict(self,key):
# # 如果key在字典里面
# if key in self.dict.keys():
# #将键对应的值返回
# return self.dict[key]
# else:
# # 如果字典里没有对应的key就返回没找到
# return "not found"
# #返回键组成的列表:返回类型;(list)
# def get_key(self,key):
# # 如果key在字典里面
# if key in self.dict.keys():
# #返回键组成的列表
# return self.dict.keys
#
# def update_dict(self,dict2):
# self.dict.update(dict2)
# return self.dict
# #创建一个字典
# dict1={'name':'小白','age':18,'hobby':'电影','sex':'男'}
# #创建第二个字典
# dict2={'id':'9527'}
# #实例化字典类
# d1=Dictclass(dict1)
# d1.del_dict('name')
# print(dict1)
# d2=d1.get_dict('age')
# print(d2)
# d3=d1.get_key("sex")
# print(d3)
# d4=d1.update_dict(dict2)
# print(d4) |
d1b88eccde187b0cead92d3d4172a6bf05d0519e | tabboud/code-problems | /problems/interview_cake/07_temperature_tracker/temperature_tracker.py | 1,587 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class TempTracker(object):
def __init__(self):
self.temps = {}
self.max_temp = None
self.min_temp = None
self.sum_of_temps = 0.0
self.num_of_temps = 0
def insert(self, new_temp):
""" Record a new temperature """
# check if temperature exists
if new_temp not in self.temps:
self.temps[new_temp] = 1
else:
self.temps[new_temp] += 1
self.sum_of_temps += new_temp
self.num_of_temps += 1
self.max_temp = max(self.max_temp, new_temp)
if self.min_temp is None:
self.min_temp = new_temp
else:
self.min_temp = min(self.min_temp, new_temp)
def get_max(self):
""" Return the highest temp we've seen so far """
return self.max_temp
def get_min(self):
""" return the lowest temp we've seen so far """
return self.min_temp
def get_mean(self):
""" return the mean of all temps seen so far """
# returns a float
return self.sum_of_temps / self.num_of_temps
def get_mode(self):
""" Return the mode of all temps seen so far """
modes = max(zip(self.temps.values(), self.temps.keys()))
return modes[1]
if __name__ == "__main__":
tracker = TempTracker()
tracker.insert(1)
tracker.insert(10)
tracker.insert(5)
tracker.insert(31)
tracker.insert(10)
print tracker.get_max()
print tracker.get_min()
print tracker.get_mean()
print tracker.get_mode()
|
03eb7da30f494d9e7c5e1748e72e5a43bf95d01f | harishdots/csv_to_nested_json | /csv_to_json/csv_to_json_tree.py | 2,354 | 3.859375 | 4 | import json
from itertools import repeat
class ConvertCsvToJsonTree:
"""
This class is used to to convert CSV data into json hierarchy tree
"""
def __init__(self, csv_data):
""" Initialising class """
self.max_column = 0
self.csv_data = csv_data
def create_parent_tree(self, is_dump_with_indent=True):
"""
- Find max columns depth in csv
- This function is used to create parent tree and push all child into it.
"""
self.max_column = int(len(self.csv_data.columns) / 3)
if is_dump_with_indent:
return json.dumps(self.add_child_to_parent(0, self.csv_data), indent=4)
else:
return json.dumps(self.add_child_to_parent(0, self.csv_data))
def add_child_to_parent(self, level, csv_data):
"""
- Starts with an empty tree/parent and add levels to the tree/parent
- Calls mapping_json_encoder function inside map to create n level children levels
:parameters:
level - data will be added as per level.
csv_data - filtered csv_data to be added as per level.
"""
if level < self.max_column:
return list(
filter(None.__ne__, list(
map(
self.mapping_json_encoder,
csv_data.iloc[:, (3 * (level + 1)) - 1].unique(),
repeat(level), repeat(csv_data)
)
))
)
else:
return []
def mapping_json_encoder(self, level_id, level, csv_data):
"""
This function is used to create mapping json encoder and add data into n level children tree,
:parameters:
level_id - this is refer to be created current level.
level - data will be added as per level.
csv_data - filtered csv_data to be added as per level
"""
csv_data = csv_data[csv_data.iloc[:, 3 * level + 2] == level_id]
if csv_data.empty:
return None
return {
"label": csv_data.iloc[:, 3 * level + 1].iloc[0].strip(),
"id": str(int(level_id)).strip(),
"link": csv_data.iloc[:, 3 * (level + 1)].iloc[0].strip(),
"children": self.add_child_to_parent((level + 1), csv_data)
}
|
6e92a2bbc8b495738d36e989f074d2a06aacb18f | Ars187/Algorithms | /Binary search.py | 675 | 4.09375 | 4 | #Binary search
def binsearch(lst,item,beg,end):
if end>=beg:
mid=(beg+end)//2
if lst[mid]==item: #If element is present at the middle itself
return(mid)
elif lst[mid]>item: #If element is smaller than mid, then it can only be present in left subarray
return(binsearch(lst,item,beg,mid-1))
#Else the element can only be present in right subarray
else:
return(binsearch(lst,item,mid+1,end))
else:
return(-1)
lst=eval(input('Enter list'))
lst.sort()
print(lst)
item=int(input('Enter no to be searched'))
beg=0
end=len(lst)-1
print(binsearch(lst,item,beg,end))
|
6d23891e169054151d934c057d59ad8e0bac393a | huyngopt1994/python-Algorithm | /green/green-08-sort/increase.py | 1,198 | 4.09375 | 4 | # Build bubble sort
my_list = []
def bubble_sort(my_list):
for i in range(len(my_list) - 1):
for j in range(i + 1, len(my_list)):
# try to swap if my_list[i] = my_list[j]
if my_list[i] > my_list[j]:
temp = my_list[i]
my_list[i] = my_list[j]
my_list[j] = temp
return my_list
my_list = [9,2,3,1,4,5,2,5]
print(bubble_sort(my_list))
# Apply insertion sort
def selectionSort(alist):
for i in range(len(alist)):
# Find the minimum element in remaining
minPosition = i
for j in range(i + 1, len(alist)):
if alist[minPosition] > alist[j]:
minPosition = j
# Swap the found minimum element with minPosition
temp = alist[i]
alist[i] = alist[minPosition]
alist[minPosition] = temp
return alist
def insertion_sort(array):
for i in range(1,len(array)):
j = i
element = array[i]
while(j>0 and array[j-1] > element):
array[j] = array[j-1]
j -=1
array[j] = element
return array
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
selectionSort(alist)
print(alist) |
6b2884b7b4e2e7d945aa49aa2515c55a51ae06e3 | mihirkelkar/hackerrank_problems | /mth-to-last-linked-list.py | 1,151 | 3.96875 | 4 | #!/usr/bin/python
class node:
def __init__(self, value):
self.value = value
self.next = None
class linkedlist:
def __init__(self):
self.head = None
self.tail = None
self.counter = 0
def add_node(self, value):
x = node(value)
if self.head == None:
self.head = x
self.tail = x
self.counter += 1
else:
self.tail.next = x
self.tail = x
self.counter += 1
def print_list(self):
cur = self.head
while(cur != None):
print cur.value
cur = cur.next
def find_nth_element(self, n):
if n > self.counter:
"""%%% Checking to see if the element that we have picked aren't actually longer than the actual linkedlist"""
print "This is impossible"
else:
npointer = self.head
cur = self.head
for i in range(0, n):
npointer = npointer.next
while(npointer != None):
npointer = npointer.next
cur = cur.next
print "Element found ",
print "The value of the element is", cur.value
def main():
ll = linkedlist()
for i in range(0, 100):
ll.add_node(i)
ll.print_list()
print ll.head.value
print ll.tail.value
ll.find_nth_element(14)
if __name__ == "__main__":
main()
|
0d627725a9c25d8e42de083e34e6aec8a7bb358c | fernandobd42/Mutation-Tool---Python | /operatorLines.py | 1,696 | 3.625 | 4 | import os # the 'os' module provides functions to interact with the operating system
import re # the 're' module provides functions to interact with regular expression operations
from data import Data # Import the class Data of file data.py
# the class OperatorLines is used to get the operators and lines of the original program
class OperatorLines():
# method used to get the current operators lines
def getOperators(self, op1, ext):
i = 0
operatorsLines = []
#selection structure used to validate if the Data.pathProject is different of 'empty'
if (Data.pathProject != ""):
path = str(Data.pathProject)
#repetition structure used to read all files of the project
for root, dirs, files in os.walk(path):
for file in files:
#selection structure used to get just files with determined ext
if file.endswith(ext):
fileMutate = os.path.join(root, file)
readFile = open(fileMutate, 'r')
# mutantFile = open(fileMutate, 'r+')
#repetion structure used to read each file with determined extension
for line in readFile:
i+=1
# mutantFile.write(re.sub(' +',' ',line))
#selection structure used to get the lines have the current operator
if(line.find(op1) > -1):
operatorsLines.append(i)
# mutantFile.close()
readFile.close()
return operatorsLines
|
7e31c62c7ab22b4f692c934b51ebe1e2f291cc04 | immortalChensm/python | /demo2/demo22.py | 515 | 3.984375 | 4 | '''
错误异常处理
try........except..........else
程序会尝试着执行语句,当语句出现错误时会匹配到except的对应错误
如果没有就执行esle语句
'''
try:
#print(3/0)
print(num)
except NameError as e:
print("不存在此变量")
except ZeroDivisionError as e:
print("被除数不能为0")
print("*"*20)
try:
print(5/0)
except:
print("程序出现了异常")
try:
print(nums)
except (NameError,ZeroDivisionError,OSError):
print("程序出错了") |
a1bb5a853291d8fa4424e4d417fdaaeba6cf470b | ianbialo/Cryptography | /app/keys_generator/prime.py | 3,610 | 3.59375 | 4 | from os import path
import random
from app.keys_generator.xorshift import XORShift
from app.utils.file_manager import read_file, write_file
from app.utils.modular_arithmetic import square_and_multiply
def _generate_possible_prime(n_bits: int = 128) -> int:
"""
Generate an odd random number of n_bits bits
:param n_bits: Number of bits of the random number
:return:
"""
xorshift = XORShift()
possible_prime = xorshift.getrandbits(n_bits)
# Make sure it is at least of the size n_bits bits
possible_prime |= (1 << (n_bits - 1))
# Make sure it is odd
possible_prime |= 1
return possible_prime
def _check_is_prime(possible_prime: int, test_rounds: int = 40) -> bool:
"""
Checks if the given number is a prime with Miller-Rabin test
:param possible_prime: The number to check
:param test_rounds: Number of test rounds for Miller-Rabin, it is the accuracy level. Internet says it should be 40
:return: True if prime
"""
# 2^s * d = n - 1
d = possible_prime - 1
s = 0
while (d & 1) == 0: # d is even
s += 1
d >>= 1 # division by 2 of even number
for i in range(test_rounds):
if not _miller_rabin_test(possible_prime, d):
return False
return True
def _miller_rabin_test(possible_prime: int, d: int) -> bool:
"""
Performs a Rabin-Miller test on a possible prime
:param d: As 2^s * d = n - 1
:param possible_prime:
:return: True if possible prime, else false
"""
a = random.randint(2, possible_prime - 2)
adn = square_and_multiply(a, d, possible_prime)
if adn == 1 or adn == possible_prime - 1:
return True
while d != possible_prime - 1:
adn = square_and_multiply(adn, 2, possible_prime)
d *= 2
if adn == 1:
return False
if adn == possible_prime - 1:
return True
return False
def get_prime(n_bits: int) -> int:
"""
Creates a safe prime of n_bits bits
:param n_bits: The number of bits of the generated safe prime
:return: The generated safe prime
"""
prime = None
while True:
prime = _generate_possible_prime(n_bits)
if _check_is_prime(prime) and _check_is_prime((prime - 1) >> 1): # Safe prime
break
return prime
def find_generator(prime: int) -> int:
"""
Finds a generator element to the given safe prime
:param prime:
:return:
"""
generator = 0
while True:
generator = random.randint(2, prime - 2)
if square_and_multiply(generator, (prime - 1) >> 1, prime) != 1:
break
return generator
class Prime:
"""
Handles a prime and its generator
"""
def __init__(self, prime_path: path, n_bits: int = 512, with_generator: bool = True):
self.__generator = 0
if path.exists(prime_path):
# Load existing prime
prime_lines = read_file(prime_path).splitlines()
self.__prime = int(prime_lines[0])
if len(prime_lines) > 1:
self.__generator = int(prime_lines[1])
else:
# Generate a new prime
self.__prime = get_prime(n_bits)
if with_generator:
self.__generator = find_generator(self.__prime)
write_file(prime_path, str(self.__prime) + '\n' + str(self.__generator))
else:
write_file(prime_path, str(self.__prime))
def get_prime(self) -> int:
return self.__prime
def get_generator(self) -> int:
return self.__generator
|
313202d0d0730500dc1fd277739c0b4d20095ecf | clarkkarenl/codingdojo_python_track | /python_stack/python_OOP/call_center/call_center.py | 3,668 | 4.25 | 4 | # Assignment: Call Center
# Karen Clark
# 2018-07-05
# You're creating a program for a call center. Every time a call comes in you need a way to track that call. One of your program's requirements is to store calls in a queue while callers wait to speak with a call center employee.
# You will create two classes. One class should be Call, the other CallCenter.
# Call Class
# * Create your call class with an init method. Each instance of Call() should have:
# Attributes:
# * unique id
# * caller name
# * caller phone number
# * time of call
# * reason for call
# Methods:
# * display: that prints all Call attributes.
class Call(object):
def __init__(self, uid, name, phone_number, time_of_call, reason):
self.uid = uid
self.name = name
self.phone_number = phone_number
self.time_of_call = time_of_call
self.reason = reason
def display(self):
print "=" * 40
print "Unique id:", self.uid
print "Caller name:", self.name
print "Caller phone number:", self.phone_number
print "Time of call:", self.time_of_call
print "Reason for call:", self.reason
return self
# CallCenter Class
# * Create your call center class with an init method. Each instance of CallCenter() should have the following attributes:
# Attributes:
# * calls: should be a list of call objects
# * queue size: should be the length of the call list
# Methods:
# * add: adds a new call to the end of the call list
# * remove: removes the call from the beginning of the list (index 0).
# * info: prints the name and phone number for each call in the queue as well as the length of the queue.
class CallCenter(object):
def __init__(self):
self.calls = []
self.queue_size = 0
def add(self, call):
self.calls.append(call)
self.queue_size += 1
return self
def remove(self):
self.calls.pop(0)
self.queue_size -= 1
return self
# Ninja Level: add a method to call center class that can find and remove a call from the queue according to the phone number of the caller.
def remove_by_pn(self, pn):
for call in self.calls:
if call.phone_number == pn:
self.calls.remove(call)
self.queue_size -= 1
return self
def info(self):
for call in self.calls:
print "|", call.name, "|", call.phone_number, "|"
print "Queue size:", self.queue_size
return self
# Hacker Level: If everything is working properly, your queue should be sorted by time, but what if your calls get out of order? Add a method to the call center class that sorts the calls in the queue according to time of call in ascending order.
def sort(self):
for i in range(0, self.queue_size):
for j in range(0, self.queue_size - i - 1):
if self.calls[j].time_of_call > self.calls[j + 1].time_of_call:
self.calls[j], self.calls[j + 1] = self.calls[j + 1], self.calls[j]
return self
caller1 = Call(1, "Apple Adams", "650-123-4567", "15:31:13", "computer won't start")
caller2 = Call(2, "Benji Benson", "650-333-4567", "16:11:43", "no internet")
caller3 = Call(3, "Charlie Chap", "650-333-9999", "17:23:54", "overcharged")
caller4 = Call(4, "David Duck", "415-234-7890", "10:01:15", "no internet")
cc1 = CallCenter()
cc1.add(caller3).add(caller1).add(caller4).add(caller2).info()
cc1.remove_by_pn("650-123-4567").info()
# cc1.sort()
# cc1.info()
# cc1.remove().info()
# You should be able to test your code to prove that it works. Remember to build one piece at a time and test as you go for easier debugging!
|
bf99b29a2c1445c8bae49125a0137b751af5e5c7 | rakeshksatapathy/python | /Maximum_Perimeter_Triangle.py | 669 | 3.8125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
#!/usr/bin/python
import sys
def Maximum_Perimeter_Triangle(n,arr) :
combo3_list=[]
triangle_list=[]
for i in xrange(n-1) :
if arr[i]+arr[i+1]>arr[i+2] and arr[i+1]+arr[i+2]>arr[i] and arr[i+2]+arr[i]>arr[i+1] :
combo3_list.append([arr[i],arr[i+1],arr[i+2]])
for i in xrange(len(combo3_list)) :
triangle_list.append(sum(combo3_list[i]))
max_value=max(triangle_list)
for i in xrange(len(triangle_list)) :
if triangle_list[i]=max_value :
index_value.append(i)
if len(index_value)=1 :
print combo3_list[i]
|
6eafcd2336a044a24472238edb9e7b94fb28f733 | jcasarru/coding-challenges | /python/4.py | 518 | 4.28125 | 4 | '''
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
(If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
'''
from math import floor
random = input('Enter a random number: ')
p_divisors = [x for x in range(1,floor(int(random)/2)+1)]
divisors = [x for x in p_divisors if int(random)%x == 0]
divisors.append(int(random))
print(divisors)
|
f918742754c615effcd3852c59714e97f7ebb05c | arturfil/data-structures-and-algorithms | /linked_lists/double_linked_list.py | 501 | 3.90625 | 4 | # Here just as the name suggest, the list has a pointer to the next and previous node which allows for faster search of values
# But is the same amount of time to delte or insert
class DoubleNode(object):
def __init__(self,value):
self.value = value
self.next = None
self.prev = None
a = DoubleNode("Head")
b = DoubleNode("First")
c = DoubleNode("Second")
d = DoubleNode("Tail")
a.next = b
b.next = c
b.prev = a
c.next = d
print(c.next.value)
print(b.next.value)
print(b.prev.value) |
dceaf2a381fe1cddc5eb44bf370b6f245d964a91 | focussash/Dynamic-Connect-4 | /Assignment 1.py | 9,673 | 3.765625 | 4 |
#Here, state will be a an array of 2 lists, First contain x coordinates of pieces, second contain y coordinates.
#In both arrays, first 6 entries are player A and next 6 are player B. The 3rd, single element of state dictates who is the moving player, 1 for A(X) and -1 for B(O).
#The 4th element is utility,1 for player A win and -1 for player B win.0 Indicates non-terminal state
#The last element is the current depth in the search tree
import copy
import time
DefaultBoard = [[1,1,1,7,7,7,1,1,1,7,7,7],[2,4,6,1,3,5,3,5,7,2,4,6],1,0,0]
TotalStatesExplored = 0
class Board:
global DefaultBoard
def __init__ (Self,InitialState = DefaultBoard):
#Initiate the board formation; if there is no input then use the default board formation
Self.State = InitialState
Self.Action = ''
Self.SearchTree = []
def Update(Self,Action):
#Apply an action (moving one piece) to update the board
X = int(Action[0])
Y = int(Action[1])
Act = Action[2]
#Now, find the piece to update
for x in range(12):
if Self.State[0][x] == X and Self.State[1][x] == Y:
PieceNumber = x
#Now, update the corresponding piece
if Act == 'N':
Self.State[1][PieceNumber] -= 1
elif Act == 'S':
Self.State[1][PieceNumber] += 1
elif Act == 'E':
Self.State[0][PieceNumber] += 1
elif Act == 'W':
Self.State[0][PieceNumber] -= 1
def GenerateBoard(State):
#This generates a bitboard of the current board (an array of 8*8 binary numbers; the bottom row and rightmost column are all 0s to avoid TerminalTest errors)
BoardArrayA = [0]*64
BoardArrayB = [0]*64
for k in range(6):
BoardArrayA[State[0][k]-1 + 8* (State[1][k]-1)] = 1
for k in range(6,12):
BoardArrayB[State[0][k]-1 + 8* (State[1][k]-1)] = 1
return BoardArrayA + BoardArrayB
def GenerateGraph(BoardArray):
#Generate a graphical representation of current board for user
#Takes input from GenerateBoard
print(' 1 2 3 4 5 6 7')
for i in range (7):
print(str(i+1), end = '')
print(' ', end = '')
for j in range (13):
if j % 2 > 0:
print(',', end = '')
else:
if BoardArray[i*8+int(j/2)] == 1:
print('X', end = '')
elif BoardArray[i*8+int(j/2)+64] == 1:
print('O', end = '')
else:
print(' ', end = '')
print('\n')
def TerminalTest(BoardArray):
#Check if the game ended; Also assigns utility: 1 = player A wins, -1 = player B wins
#Takes input from GenerateBoard
StrA = "".join(map(str, BoardArray[0:63]))
StrB = "".join(map(str, BoardArray[64:128]))
BitNumA = int(StrA,base = 2)
BitNumB = int(StrB,base = 2)
#Horizontal
if BitNumA & BitNumA >> 1 & BitNumA >> 2 & BitNumA >> 3:
return 1
if BitNumB & BitNumB >> 1 & BitNumB >> 2 & BitNumB >> 3:
return -1
#Vertical
if BitNumA & BitNumA >> 8 & BitNumA >> 16 & BitNumA >> 24:
return 1
if BitNumB & BitNumB >> 8 & BitNumB >> 16 & BitNumB >> 24:
return -1
#Two kinds of diagnal (right and left, respectively)
if BitNumA & BitNumA >> 9 & BitNumA >> 18 & BitNumA >> 27:
return 1
if BitNumB & BitNumB >> 9 & BitNumB >> 18 & BitNumB >> 27:
return -1
if BitNumA & BitNumA >> 7 & BitNumA >> 14 & BitNumA >> 21:
return 1
if BitNumB & BitNumB >> 7 & BitNumB >> 14 & BitNumB >> 21:
return -1
#If noone won
return 0
def GenerateChild(State):
#Generate all child nodes of a given node
#The check for terminal does not happen within this function, rather before calling this function
#Takes input directly from Board State, as defined at the beginning of this file
#Start by picking a piece in the board
ChildTemp = copy.deepcopy(State)
ChildTemp[2] *= -1 #In the child, it's next player's term
ChildAll = []
DuplicateCheck = []
del_list = [] #Store the list of nodes that overlaps pieces
if State[2] == 1:
player = range(6)
else:
player = range(6,12)
for i in player:
if ChildTemp[0][i] != 1:
ChildTemp[0][i] -= 1 #Applying 'W'
ChildTemp[4] += 1
ChildAll.append(ChildTemp)
ChildTemp = copy.deepcopy(State)
ChildTemp[2] *= -1
if ChildTemp[0][i] != 7:
ChildTemp[0][i] += 1 #Applying 'E'
ChildTemp[4] += 1
ChildAll.append(ChildTemp)
ChildTemp = copy.deepcopy(State)
ChildTemp[2] *= -1
if ChildTemp[1][i] != 1:
ChildTemp[1][i] -= 1 #Applying 'S'
ChildTemp[4] += 1
ChildAll.append(ChildTemp)
ChildTemp = copy.deepcopy(State)
ChildTemp[2] *= -1
if ChildTemp[1][i] != 7:
ChildTemp[1][i] += 1 #Applying 'N'
ChildTemp[4] += 1
ChildAll.append(ChildTemp)
ChildTemp = copy.deepcopy(State)
ChildTemp[2] *= -1
#Now, check if the move causes 2 pieces to overlap
for j in range(len(ChildAll)):
for k in range(12):
DuplicateCheck.append([ChildAll[j][0][k],ChildAll[j][1][k]])
if len(DuplicateCheck) != len(set(map(tuple,DuplicateCheck))):
del_list.append(ChildAll[j])
DuplicateCheck.clear()
for p in range(len(del_list)):
ChildAll.remove(del_list[p])
#Now check if anyone won and update accordingly
for q in range(len(ChildAll)):
ChildAll[q][3] = TerminalTest(GenerateBoard(ChildAll[q]))
return ChildAll
def Max_Utility(State,cutoff):
global TotalStatesExplored
Child = GenerateChild(State)
if State[3] != 0: #If we already are at a leaf node
PerformanceEval()
return State
elif State[4] == cutoff: #Or if we passed the depth limit
State[3] = Heuristics(State)
PerformanceEval()
return State
utility = - 100 #Technically this needs to be -inf but our utility don't go that far
for i in range(len(Child)):
utility = max(utility,Min_Utility(Child[i],cutoff)[3])
State[3] = utility
PerformanceEval()
return State
def Min_Utility(State,cutoff):
global TotalStatesExplored
Child = GenerateChild(State)
if State[3] != 0: #If we already are at a leaf node
PerformanceEval()
return State
elif State[4] == cutoff: #Or if we passed the depth limit
State[3] = Heuristics(State)
PerformanceEval()
return State
utility = 100 #Technically this needs to be inf but again our utility don't go that far
for i in range(len(Child)):
utility = min(utility,Max_Utility(Child[i],cutoff)[3])
State[3] = utility
PerformanceEval()
return State
def minmax(State,cutoff):
#This function applys minmax algorithm to find the next best move, given a step cutoff
#It returns an action to be taken
NextBoard = [] #This stores the board after the next best move, with this we can retrack the best action to take
FindAction = []
Action = []
UtilityResults =[]
Max,Min = 0,1000
MaxIndex, MinIndex = 0,0
Child = []
#First, find the board after the next best move
Child = GenerateChild(State)
if State[2] == 1: #Player A's turn
for i in range(len(Child)):
UtilityResults.append(Max_Utility(Child[i],cutoff))
for j in range (len(UtilityResults)):
if Max < UtilityResults[j][3]:
Max = UtilityResults[j][3]
MaxIndex = j
NextBoard = UtilityResults[MaxIndex]
elif State[2] == -1: #Player B's turn
for i in range(len(Child)):
UtilityResults.append(Min_Utility(Child[i],cutoff))
for j in range (len(UtilityResults)):
if Min > UtilityResults[j][3]:
Min = UtilityResults[j][3]
MinIndex = j
NextBoard = UtilityResults[MinIndex]
#Now backtrack which move causes this board?
for j in range(12):
if State[0][j] > NextBoard[0][j]:
Action.append(str(State[0][j]))
Action.append(str(State[1][j]))
Action.append('W')
elif State[0][j] < NextBoard[0][j]:
Action.append(str(State[0][j]))
Action.append(str(State[1][j]))
Action.append('E')
elif State[1][j] > NextBoard[1][j]:
Action.append(str(State[0][j]))
Action.append(str(State[1][j]))
Action.append('N')
elif State[1][j] < NextBoard[1][j]:
Action.append(str(State[0][j]))
Action.append(str(State[1][j]))
Action.append('S')
return ''.join(Action)
def Heuristics(State):
#Gives the heuristic evaluation of current state
return 1
def PerformanceEval():
global TotalStatesExplored
TotalStatesExplored += 1
#print(TotalStatesExplored)
#start_time = time.time()
cB = [[3,7,6,7,7,4,1,4,5,6,3,5],[2,4,5,5,6,7,3,4,5,6,6,7],-1,0,0]
a = Board(cB)
#print(minmax(a.State,2))
#print(TotalStatesExplored)
#print("--- %s seconds ---" % (time.time() - start_time))
|
9af72152c8c14f53cfd9e06fc0ada38f99558456 | ashishsahu1/ImageProcessing | /InvisibilityCloak/background.py | 713 | 3.53125 | 4 | #------------------------------------------------------------------------------
#first step is to click a background image
#second step select the colour
#it should remove every pixel which is red and change with background
#------------------------------------------------------------------------------
#importing libraries
import cv2
cap=cv2.VideoCapture(0)
while cap.isOpened():
ret,back=cap.read()#reading from webcam
#ret is true if camera is recalled otherwise its false
if ret:
cv2.imshow("image",back)
if cv2.waitKey(5)==ord('q'):
# when pressed q save the image
cv2.imwrite('image.jpg',back)
break
cap.release()
cv2.destroyAllWindows()
|
282b9ab8996c8b69492f34404345159ba4aae0ac | bitcocom/python | /Python중급1/section4/4-3-1.py | 1,299 | 3.78125 | 4 | #리스트 자료형(순서O, 중복O, 수정O, 삭제O)
#선언
a = []
b = list()
c = [0, 0, 1, 2]
d = [0, 1, 'car', 'apple', 'apart']
e = [0, 1, ['car', 'apple', 'apart']]
#인덱싱
print('#=====#')
print('d - ',type(d),d)
print('d - ',d[1])
print('d - ',d[0]+d[1]+d[1])
print('d - ',d[-1])
print('e - ',e[-1][1])
print('e - ',e[-1][1][4])
print('e - ',list(e[-1][1]))
#슬라이싱
print('#=====#')
print('d - ',d[0:3])
print('d - ',d[2:])
print('e - ',e[2][1:3])
#리스트 연산
print('#=====#')
print('c + d - ',c + d)
print('c * 3 - ',c * 3)
#print("c[0] + 'hi' - ",c[0] + 'hi')
print("'hi' + c[0] - ",'hi' + str(c[0]))
#리스트 수정, 삭제
print('#=====#')
c[0] = 4
print('c - ', c)
c[1:2] = ['a', 'b', 'c']
print('c - ', c)
c[1] = ['a', 'b', 'c']
print('c - ', c)
c[1:3] = []
print('c - ', c)
del c[3]
print('c - ', c)
#리스트 함수
a = [5, 2, 3, 1, 4]
print('a - ', a)
a.append(6)
print('a - ', a)
a.sort()
print('a - ', a)
a.reverse()
print('a - ', a)
print('a - ', a.index(5))
a.insert(2,7)
print('a - ', a)
a.reverse()
a.remove(1)
print('a - ', a)
print('a - ', a.pop())
print('a - ', a.pop())
print('a - ', a)
print('a - ', a.count(4))
ex = [8, 9]
a.extend(ex)
print('a - ', a)
#삭제 remove, pop, del
#반복문 활용
while a:
l = a.pop()
print(2 is l)
|
6f6134c34b980363974571f21e64c746b602daf5 | chelseealee/swarch | /server-master/client.py | 2,578 | 3.6875 | 4 | """
The Client is slave:
- it sends only the player inputs to the server.
- every frame, it displays the server's last received data
Pros: the server is the only component with game logic,
so all clients see the same game at the same time (consistency, no rollbacks).
Cons: lag between player input and screen display (one round-trip).
But the client can smooth the lag by interpolating the position of the boxes.
"""
from network import Handler, poll
from pygame import Rect, init as init_pygame
from pygame.display import set_mode, update as update_pygame_display
from pygame.draw import rect as draw_rect
from pygame.event import get as get_pygame_events
from pygame.locals import KEYDOWN, QUIT, K_ESCAPE, K_UP, K_DOWN, K_LEFT, K_RIGHT
from pygame.time import Clock
borders = []
pellets = []
players = {} # map player name to rectangle
myname = None
init_pygame()
screen = set_mode((400, 300))
clock = Clock()
def make_rect(quad): # make a pygame.Rect from a list of 4 integers
x, y, w, h = quad
return Rect(x, y, w, h)
class Client(Handler):
def on_msg(self, data):
global borders, pellets, players, myname
borders = [make_rect(b) for b in data['borders']]
pellets = [make_rect(p) for p in data['pellets']]
players = {name: make_rect(p) for name, p in data['players'].items()}
myname = data['myname']
client = Client('localhost', 8888) # connect asynchronously
valid_inputs = {K_UP: 'up', K_DOWN: 'down', K_LEFT: 'left', K_RIGHT: 'right'}
while 1:
poll() # push and pull network messages
# send valid inputs to the server
for event in get_pygame_events():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
key = event.key
if key == K_ESCAPE:
exit()
elif key in valid_inputs:
msg = {'input': valid_inputs[key]}
client.do_send(msg)
# draw everything
screen.fill((0, 0, 64)) # dark blue
[draw_rect(screen, (0, 191, 255), b) for b in borders] # deep sky blue
[draw_rect(screen, (255, 192, 203), p) for p in pellets] # shrimp
for name, p in players.items():
if name != myname:
draw_rect(screen, (255, 0, 0), p) # red
if myname:
draw_rect(screen, (0, 191, 255), players[myname]) # deep sky blue
update_pygame_display()
clock.tick(50) # frames per second, independent of server frame rate
|
8a0dacf1f937a131717fff1e53bedbb07209b1a4 | DylanBarrett/IT1040-Mizzou | /BarrettDylanAnimals/Animal.py | 816 | 4.125 | 4 | import random
# This program creates a class named
# Animal and stores information about an animal.
class Animal:
# The __init__ method initializes the attribute
def __init__(self, animal_type, name):
self.__animal_type = animal_type
self.__name = name
a = random.randint(1,3)
if a ==1:
self.__mood = 'happy'
if a ==2:
self.__mood = 'hungry'
if a ==3:
self.__mood = 'sleepy'
# get_animal_type returns the type of animal
def get_animal_type(self):
return self.__animal_type
# get_name returns the name of the animal
def get_name(self):
return self.__name
# check_mood return the mood of the animal
def check_mood(self):
return self.__mood
|
4d02ec010dd06b51657f0a7209da9bbfc0e5cc69 | ClaudiaStrm/Introducao_ciencia_da_computacao | /02-01_raiz.py | 1,090 | 3.8125 | 4 | '''O programa deve receber os parâmetros a, b, e c da equação ax2+bx+c, respectivamente,
e imprimir o resultado na saída da seguinte maneira:
Quando não houver raízes reais imprima: esta equação não possui raízes reais
Quando houver apenas uma raiz real imprima: a raiz desta equação é onde X é o valor da raiz
Quando houver duas raízes reais imprima: as raízes da equação são X e Y onde X e Y são os valor das raízes.
Além disto, no caso de existirem 2 raízes reais, elas devem ser impressas em ordem crescente, ou seja,
X deve ser menor ou igual a Y.
'''
import math
a = float(input("Valor de a: "))
b = float(input("Valor de b: "))
c = float(input("Valor de c: "))
delta = b ** 2 - 4 * a * c
if a == 0 or delta < 0:
print("esta equação não possui raízes reais")
elif delta == 0:
raiz1 = (- b )/ (2 * a)
print("a raiz desta equação é %.3f" %raiz1)
else:
raiz1 = (- b + math.sqrt(delta)) / (2 * a)
raiz2 = (- b - math.sqrt(delta)) / (2 * a)
a = min(raiz1, raiz2)
b = max(raiz1, raiz2)
print("as raízes da equação são %f e %f" %(a, b)) |
7678e0c931404b167888bc265f26f4e6e0b597be | Henryzhaoheran/boo-vscode | /listgen.py | 477 | 4.0625 | 4 | # List generator P42
# 列表生成式和列表生成器的不同
l = ("{}*{}".format(x, x) for x in range(1, 11))
print(l)
"""
print(next(l))
print(next(l))
print(next(l))
print(next(l))
"""
for idx in range(1, 11):
print(next(l), end = ' ')
print()
#判断为偶数
l1 = ("_{}_".format(x) for x in range(1, 11) if x%2 == 0)
print(l1)
"""
print(next(l))
print(next(l))
print(next(l))
print(next(l))
"""
for idx in range(1, 6):
print(next(l1), end = ' ')
print()
|
4bf7015c7579f72c48db9dd2ff0177171921092f | rmesquita91/bdpython | /dadosimc.python.py | 743 | 3.859375 | 4 | import sqlite3
# criar uma conexão e um cursor
con = sqlite3.connect('dadosimc.db')
cur = con.cursor()
#SQL linguagem criar tabela
sql = 'create table dados'\
'(id integer primary key,'\
' nome varchar (100) NOT NULL,'\
'altura varchar(10)NOT NULL,'\
'peso varchar(10)NOT NULL,))
cur.execute(sql)
#fechar a conexao
con.close()
Print ("Dados IMC criado com sucesso")
#inserir dados na tabela
sql = 'insert into dados values (nome, altura, peso) values ('Rafael','1,90','80.0')
#gravando no banco
con.commit()
print('Dados inseridos com sucesso.')
con.close
#Realizado o calculo IMC
sql ='select from dados values(peso/(altura*altura))'
print('Dados inseridos')
|
f6df97239d04a174750ec44fc165c4df01763fdb | payscale/payscale-course-materials | /python/software_engineering/solutions/employee_example.py | 742 | 3.921875 | 4 | class Employee:
def __init__(self, name, job_title, job_location):
self.name = name
self.job_title = job_title
self.job_location = job_location
def greeting(self):
return f"Hello, my name is {self.name} and I am a {self.job_title}"
def estimated_salary(self):
if self.job_title == "Software Engineer":
if self.job_location == "San Francisco":
return "150K"
elif self.location == "Dallas":
return "90K"
else:
return "70K"
else:
return "40K"
jamie = Employee("Jamie", "Software Engineer", "San Francisco")
print(jamie.greeting())
print("Jamie's salary is", jamie.estimated_salary())
|
a381a61c093506f8592138f288c93ee4a22266b2 | smartarch/qoscloud | /cloud_controller/analyzer/objective_function.py | 4,496 | 3.53125 | 4 | """
This module contains the class creating the objective function expression. The objective is represented as an integer
expression which is supposed to be added to CSP solver.
The abstract class ObjectiveFunction can be used to implement new objective functions.
"""
import time
from abc import abstractmethod
from typing import Optional, List
import logging
from ortools.constraint_solver.pywrapcp import IntVar, OptimizeVar, Solver, IntExpr
from cloud_controller import CSP_RUNNING_NODE_COST, CSP_LATENCY_COST, CSP_REDEPLOYMENT_COST
from cloud_controller.analyzer.constraint import Constraint
from cloud_controller.analyzer.variables import Variables
class ObjectiveFunction(Constraint):
def __init__(self):
super().__init__()
self.cost_var: Optional[IntVar] = None
self.objective: Optional[OptimizeVar] = None
@abstractmethod
def expression(self, variables: Variables):
pass
def add(self, solver: Solver, variables: Variables):
self.cost_var: IntVar = solver.IntVar(0, 100000, "Total cost")
solver.Add(self.cost_var == self.expression(variables))
self.objective: OptimizeVar = solver.Minimize(self.cost_var, 1)
class DefaultObjectiveFunction(ObjectiveFunction):
def expression(self, variables: Variables):
"""
Creates an integer expression the value of which shows the "cost" of a given solution. Based on the value of this
expression, the solver can judge whether one solution is better than the other. The value of the expression should
be minimized. The expression consists of three terms with different weights.
(1) First of all, we aim to minimize the latency between the client and its servers. Thus, we should always
prefer the solutions where all the client dependencies are located on the closest server.
(2) Then, we try to minimize the number of managed compin redeployments. There is no need to change the location
of an already deployed compin unless the client moves to another datacenter.
(3) Finally, we prefer those solutions which use the smallest number of nodes.
:return: The created expression.
"""
start = time.perf_counter()
nodes = self._create_running_nodes_expression(variables)
logging.debug(f"Nodes objective adding time: {(time.perf_counter() - start):.15f}")
start = time.perf_counter()
redeployment = self._create_redeployment_expression(variables)
logging.debug(f"Redeployment objective adding time: {(time.perf_counter() - start):.15f}")
start = time.perf_counter()
latency = self._create_latency_expression(variables)
logging.debug(f"Latency objective adding time: {(time.perf_counter() - start):.15f}")
return redeployment + nodes + latency
def _create_latency_expression(self, variables: Variables) -> IntExpr:
"""
Creates expression representing the cost of the latencies between clients and the datacenters they are connected to.
"""
latency_expressions: List[IntExpr] = []
for tier in variables.client_dc_vars_by_tier:
latency_expressions.append(tier * (sum([var.int_var for var in variables.client_dc_vars_by_tier[tier]])))
expr = CSP_LATENCY_COST * (sum(latency_expressions))
logging.debug(f"Client latency expression = {expr}")
return expr
def _create_running_nodes_expression(self, variables: Variables) -> IntExpr:
"""
Creates expression representing the number of running nodes.
"""
running_node_vars_sum: IntExpr = sum([var.int_var for var in variables.running_node_vars.values()])
expr = CSP_RUNNING_NODE_COST * running_node_vars_sum
logging.debug(f"Running nodes expression = {expr}")
return expr
def _create_redeployment_expression(self, variables: Variables) -> IntExpr:
"""
Creates expression representing the number of compin redeployments.
"""
redeploy_vars_sum: IntExpr = sum([var.int_var
for _ in variables.running_vars_by_node_and_compin.values()
for var in _.values()
])
expr = CSP_REDEPLOYMENT_COST * redeploy_vars_sum
logging.debug(f"Redeployment expression = {expr}")
return expr
|
10657ac14bfe925ca5560da05c6308c670e7a82c | noahadelstein/mathemagic | /sample_python/attendee (2013).py | 1,150 | 3.5625 | 4 | #-------------------------------------------------------------------------------
# Name: attendee.py
# Purpose: keeps track of name, company, state, and email address
#
# Author: Adrienne Sands
#
# Created: 22/05/2013
# Copyright: (c) Adrienne Sands 2013
#-------------------------------------------------------------------------------
class Attendee:
def __init__(self,name,company,state,emailAddress):
self.name = name
self.company = company
self.state = state
self.emailAddress = emailAddress
def getInfo(self,string):
output = []
if ("name" in string) or string=="all":
output.append(self.name)
if ("email" in string) or string=="all":
output.append(self.emailAddress)
if ("company" in string) or string=="all":
output.append(self.company)
if ("state" in string) or string=="all":
output.append(self.state)
return output
def getState(self):
return self.state
def getNameEmail(self):
return self.name,self.emailAddress
def main():
pass
if __name__ == '__main__':
main()
|
3ca75c9d38a50e449c9dacc317045deff0a6f680 | bimarakajati/Dasar-Pemrograman | /Materi/Materi 7 Pengulangan Bersarang/nestloop.py | 329 | 4.03125 | 4 | for i in range(1,4): # Outer Loop
print ("Outer Loop ke - ",i)
for j in range(1,3): # Inner Loop
print (" - Inner Loop ke - ",j)
print("selesai")
a = 1
while (a < 4) :
print ("Outer Loop ke - ",a)
b = 1
while (b < 3) :
print ("* Inner Loop ke - ",b)
b+=1
a+=1
print ("")
print("selesai")
|
b458910d53b2e63d4732adff493764bcc6ddc11d | Magorx/ray_tracing | /vector.py | 2,836 | 3.765625 | 4 | from math import sqrt, sin, cos
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return Vector(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
def len(self):
return sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def normal(self):
length = self.len()
if length == 0:
return Vector(0, 0, 0)
else:
return Vector(self.x / length, self.y / length, self.z / length)
def proection(self, other):
return self.normal() * self.dot(other.normal()) * other.len()
def to_ints(self):
return Vector(int(self.x), int(self.y), int(self.z))
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, other):
if isinstance(other, Vector):
return Vector(self.x * other.x, self.y * other.y, self.z * other.z)
else:
assert type(other) == float or type(other) == int
return Vector(self.x * other, self.y * other, self.z * other)
def __truediv__(self, other):
if isinstance(other, Vector):
return Vector(self.x / other.x, self.y / other.y, self.z / other.z)
else:
assert type(other) == float or type(other) == int
return Vector(self.x / other, self.y / other, self.z / other)
def __pow__(self, other):
return Vector(self.x ** other, self.y ** other, self.z ** other)
def __repr__(self):
return '{' + '{}, {}, {}'.format(self.x, self.y, self.z) + '}'
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z
def __lt__(self, other):
return self.x < other.x or self.y < other.y or self.z < other.z
def rotx(vec, ang):
x = vec.x
y = vec.y * cos(ang) - vec.z * sin(ang)
z = vec.y * sin(ang) + vec.z * cos(ang)
return Vector(x, y, z)
def roty(vec, ang):
x = vec.x * cos(ang) + vec.z * sin(ang)
y = vec.y
z = vec.z * cos(ang) - vec.x * sin(ang)
return Vector(x, y, z)
def rotz(vec, ang):
x = vec.x * cos(ang) - vec.y * sin(ang)
y = vec.y * cos(ang) - vec.x * sin(ang)
z = vec.z
return Vector(x, y, z)
def rot(vec, dx=0, dy=0, dz=0, rotation=()):
if rotation:
dx = rotation[0]
dy = rotation[1]
dz = rotation[2]
if dx == 0 and dy == 0 and dz == 0:
return vec * 1
return rotz(roty(rotx(vec, dx), dy), dz)
|
f5d2c2ab691ae22d532358f7046c5847db421a17 | road-to-koshien/kevin-leetcode-challenge | /LEETCODE/coin change(WIP).py | 1,071 | 3.828125 | 4 | # You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
# Example 1:
# Input: coins = [1, 2, 5], amount = 11
# Output: 3
# Explanation: 11 = 5 + 5 + 1
# Example 2:
# Input: coins = [2], amount = 3
# Output: -1
# Note:
# You may assume that you have an infinite number of each kind of coin.
A = "s z z z s"
B = "s z ejt"
result = []
list_del = []
list_a = A.split()
list_b = B.split()
list_aset = list(set(list_a))
list_bset = list(set(list_b))
print(list_a.count('s'))
for each in list_aset:
if list_a.count(each) > 1:
list_aset.remove(each)
continue
print(list_aset)
for each in list_bset:
if list_b.count(each) > 1:
list_bset.remove(each)
for each in list_aset:
if each in list_bset:
list_del.append(each)
for each in list_del:
list_aset.remove(each)
list_bset.remove(each)
result = list_aset + list_bset
|
7040ff09c5d9c8ebf2a5a3cca5c05f912bb22e94 | wintersalmon/tic-tac-toe | /tests/test_board.py | 3,664 | 3.953125 | 4 | '''
TestCase For Board
'''
from unittest import TestCase, main
from tictactoe.board import Board
class TestBoardCreate(TestCase):
'''Represents Board Create TestCases'''
def test_crete_invalid_size(self):
'''Test Board Creation with INVLID number'''
self.assertRaises(ValueError, Board, 1)
self.assertRaises(ValueError, Board, 2)
self.assertRaises(ValueError, Board, -3)
self.assertRaises(ValueError, Board, -2)
def test_create_even_size(self):
'''Test Board Creation with EVEN number'''
self.assertRaises(ValueError, Board, 4)
self.assertRaises(ValueError, Board, 6)
self.assertRaises(ValueError, Board, 8)
self.assertRaises(ValueError, Board, 100)
def test_create_odd_size(self):
'''Test Board Creation with ODD number'''
Board(3)
Board(5)
Board(7)
Board(99)
class TestBoardHasStraightLine(TestCase):
'''Represents Board Pattern Check TestCases'''
def setUp(self):
self.board_size_list = [3, 5, 9]
self.sample_values = [-9999999, -1, 0, 1, 9999999]
def tearDown(self):
self.board_size_list = None
def test_board_not_straight_line(self):
'''Test Board not has_straight_line horizontal'''
for size in self.board_size_list:
board = Board(size)
self.assertTrue(not board.has_straight_line())
def test_board_horizontal_line(self):
'''Test Board has_straight_line horizontal'''
for size in self.board_size_list:
for value in self.sample_values:
for row in range(size):
board = Board(size)
self._fill_board_horizontally(board, value=value, row=row)
self.assertTrue(board.has_straight_line())
def test_board_vertical_line(self):
'''Test Board has_straight_line vertical'''
for size in self.board_size_list:
for value in self.sample_values:
for col in range(size):
board = Board(size)
self._fill_board_vertically(board, value=value, col=col)
self.assertTrue(board.has_straight_line())
def test_board_diagnal_line(self):
'''Test Board has_straight_line diagnal'''
for size in self.board_size_list:
for value in self.sample_values:
board = Board(size)
self._fill_board_diagnally(board, value=value)
self.assertTrue(board.has_straight_line())
for size in self.board_size_list:
for value in self.sample_values:
board = Board(size)
self._fill_board_diagnally(board, value=value, direction=1)
self.assertTrue(board.has_straight_line())
def _fill_board_horizontally(self, board, *, value, row):
'''fill board horizontally with value'''
for col in range(board.max_col):
board.set_value_at(row, col, value)
def _fill_board_vertically(self, board, *, value, col):
'''fill board vertically with value'''
for row in range(board.max_row):
board.set_value_at(row, col, value)
def _fill_board_diagnally(self, board, *, value, direction=0):
'''fill board diagnally with value'''
max_idx = board.max_row
for idx in range(max_idx):
row = idx
if direction: # LeftTop to RightBottom
col = idx
else: # RightTop to LeftBottom
col = max_idx - idx - 1
board.set_value_at(row, col, value)
if __name__ == "__main__":
main()
|
ab5dd6a3c424eac9a5ac8d1159b4476d2290e571 | abbyschantz/cs35 | /hw0/hw0pr2.py | 5,875 | 3.703125 | 4 | # hw0pr2.pr
#
# Eliana Keinan, Liz Harder, Abby Schantz
import os
import os.path
def count_files():
""" counts the number of .txt files in the folder
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
count = 0
for foldername in L[1:]:
files = os.listdir(foldername)
os.chdir(foldername)
for filename in files:
count += 1
os.chdir("..")
os.chdir("..")
return count
def count_ten():
""" returns the number of phone numbers that contian exactly 10 digits
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
count = 0
for foldername in L[1:]:
files = os.listdir(foldername)
os.chdir(foldername)
for filename in files:
if count_digits(filename) == 10:
count += 1
os.chdir("..")
os.chdir("..")
return count
def count_digits(filename):
""" counts the number of digits in a phone number file
"""
file = open(filename,"r")
text = file.read()
count = 0
for i in range(len(text)):
if text[i] in '0123456789':
count += 1
return count
def is909(filename):
""" checks if the number is in the area code 909
"""
file = open(filename,"r")
text = file.read()
text = clean_digits(text)
if len(text) == 10 and text[0:3] == '909':
return True
else:
return False
def clean_digits(s):
""" returns only the digits in the input string s
"""
new_string = ''
for i in range(len(s)):
if s[i] in '1234567890':
new_string += s[i]
return new_string
def count_909():
""" returns the number of phone numbers that are in the 909 area code
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
count = 0
for foldername in L[1:]:
files = os.listdir(foldername)
os.chdir(foldername)
for filename in files:
if is909(filename):
count += 1
os.chdir("..")
os.chdir("..")
return count
def count_garcia():
""" returns the number of phone files that contain Garcia
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
count = 0
for foldername in L[1:]:
files = os.listdir(foldername)
os.chdir(foldername)
for filename in files:
if isGarcia(filename):
count += 1
os.chdir("..")
os.chdir("..")
return count
def isGarcia(filename):
""" checks if the file contains the name Garcia
"""
file = open(filename,"r")
text = file.read()
text = text.lower()
if 'garcia' in text:
return True
def contains42(filename):
""" checks if the phone number has the substring 42 in it
"""
file = open(filename, "r")
text = file.read()
text = clean_digits(text)
if '42' in text:
return True
def count_42():
""" returns the number of phone numbers that contain the substring 42
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
count = 0
for foldername in L[1:]:
files = os.listdir(foldername)
os.chdir(foldername)
for filename in files:
if contains42(filename):
count += 1
os.chdir("..")
os.chdir("..")
return count
def count_garcia_by_areacode():
""" returns the number of "GARCIA"s in each area code
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
d = {}
count = 0
for foldername in L[1:]:
files = os.listdir(foldername)
os.chdir(foldername)
for filename in files:
if isGarcia(filename):
if areacode(filename) in d:
d[areacode(filename)] += 1
else:
d[areacode(filename)] = 1
os.chdir("..")
os.chdir("..")
return d
def areacode(filename):
""" returns the areacode
"""
file = open(filename,"r")
text = file.read()
text = clean_digits(text)
return text[0:3]
def isSameNum(filename):
""" checks if the first number in the phone number is the same as
the last number. Returns True or False
"""
file = open(filename,"r")
text = file.read()
text = clean_digits(text)
if text[0] == text[-1]:
print (text)
return True
else:
return False
def count_SameNum():
""" returns the number of phone numbers that begin and end with the same number
"""
L = os.listdir("phone_files")
os.chdir( "phone_files" )
count = 0
for foldername in L[1:]:
files = os.listdir(foldername)
os.chdir(foldername)
for filename in files:
if isSameNum(filename):
count += 1
os.chdir("..")
os.chdir("..")
return count
def main():
print("There are ", count_garcia_by_areacode(), " 'GARCIA' in each area code")
print("There are ", count_files(), " .txt files in the whole set.")
print("There are ", count_ten(), " phone numbers that are exactly 10 digits.")
print("There are ", count_909(), " phone numbers that are in 909.")
print("There are ", count_garcia(), " people with the name 'GARCIA' in the whole set.")
print("There are ", count_42(), "phone numbers that contain the string '42'.")
print("There are ", count_SameNum(), " phone numbers that begin and end with the same digit.")
"""
ANSWERS:
1. There are 9896 .txt files in the whole set.
2. There are 3988 phone numbers that are exactly 10 digits.
3. There are 9 phone numbers that are in 909.
4. There are 237 people with the name "GARCIA" in the whole set.
5. There are 671 phone numbers that contain the string "42".
""" |
9ba53a27428c23be311befd2bb5822d83eab8ef0 | mkozigithub/mkgh_info_python | /20190111 FCSA Learning Time/Files/PythonBeyondTheBasics/07_iterables_iteration/reduce.py | 899 | 4.1875 | 4 | # reduce repeatedly applies a function to elements of a sequence, reducing them to a single value
from functools import reduce
import operator
sum = reduce(operator.add, [1, 2, 3, 4, 5])
print(sum)
# functionally equivalent to:
numbers = [1, 2, 3, 4, 5]
accumulator = operator.add(numbers[0], numbers[1])
for item in numbers[:2]:
accumulator = operator.add(accumulator, item)
print(accumulator)
def mul(x, y):
print(f'mul {x} {y}')
return x * y
result = reduce(mul, range(1,10))
print(result)
# reduce(mul, []) # empty list raises exception
print(reduce(mul, [1])) # list with one element returns element without running function
# optional initial value
values = [1, 2, 3]
print(reduce(operator.add, values, 0))
values = []
print(reduce(operator.add, values, 0)) # when optional initializer is supplied, empty list argument doesn't raise exception |
abd817de2e101f5c4e97a5096398d926dd6d4256 | siddharth20190428/DEVSNEST-DSA | /DI017_Binary_tree_level_order_traversal.py | 785 | 3.9375 | 4 | """
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
----------------
Constraints
The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
"""
from DI015_Trees import TreeNode
def levelOrder(root):
if not root:
return []
ans = [[]]
x = "X"
q = [root, x]
while True:
n = q.pop(0)
if n == x:
if len(q) == 0:
return ans
q.append(x)
ans.append([])
else:
ans[-1].append(n.val)
if n.left:
q.append(n.left)
if n.right:
q.append(n.right)
root = [3, 9, 20, None, None, 15, 7]
# root = [1]
# root = [] |
4083fb2b010e8d798ecbdf22fe69a75f40a78804 | vkd8756/Python | /ll/circular_doubly_ll.py | 2,098 | 3.6875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
self.prev=None
class Cdll:
def __init__(self):
self.head=None
def epush(self,x):
temp=self.head
new_node=Node(x)
if not temp:
self.head=new_node
self.head.next=new_node
self.head.prev=new_node
return
while temp.next!=self.head:
temp=temp.next
temp.next=new_node
new_node.prev=temp
new_node.next=self.head
def fpush(self,x):
temp=self.head
new_node=Node(x)
if not temp:
self.head=new_node
self.head.next=new_node
self.head.prev=new_node
return
while temp.next!=self.head:
temp=temp.next
temp.next=new_node
new_node.prev=temp
new_node.next=self.head
self.head=new_node
def pop(self):
temp=self.head
if not temp.next:
self.head=None
self.next=None
self.prev=None
return
while temp.next!=self.head:
temp=temp.next
temp.next=self.head.next
self.head=self.head.next
self.head.prev=temp
def pop_item(self,x):
temp=self.head
if temp.data==x:
self.pop()
return
while temp.data!=x and temp.next!=self.head:
temp=temp.next
if not temp:
return
prv=temp.prev
nxt=temp.next
prv.next=nxt
def pl(self):
temp=self.head
while temp:
print(temp.data,"-->",end="")
temp=temp.next
if temp==self.head:
print(temp.data)
break
if __name__=="__main__":
cdll=Cdll()
cdll.epush(1)
cdll.pl()
cdll.epush(2)
cdll.pl()
cdll.epush(3)
cdll.epush(4)
cdll.pl()
cdll.pop()
cdll.pl()
cdll.pop_item(4)
cdll.pl()
cdll.fpush(5)
cdll.pl()
|
d2bf036b43b44391f48f9a8e3f7d180ca777a6be | jaykiran/Beginner_Programming_challenges_lco | /python_answers/question6.py | 278 | 3.9375 | 4 | f = int(input("enter free bytes"))
u = int(input("enter used bytes"))
o = int(input("enter deleted bytes"))
n = int(input("enter created bytes"))
disksize = f+u
currentlyused = u-o
currentlyused = currentlyused + n
currentlyfree = disksize - currentlyused
print(currentlyfree) |
efa216210ab36330d6a58baf9f83952349f81c8f | ThyagoHiggins/LP-Phython | /Aulas e Exercicios/Exercicios/Lista 2/Exercicio 1.py | 789 | 3.875 | 4 | sal = float(input('Informe o salário: R$ '))
if sal <= 600.00:
desconto= sal*0.07
print(f'O valor de contribução ao INSS é de {desconto:.2f}\n'
f'Logo seu Salário final é R$ {sal-desconto:.2f}')
if sal >= 600.01 and sal <= 800:
desconto = sal * 0.08
print(f'O valor de contribução ao INSS é de {desconto:.2f}\n'
f'Logo seu Salário final é R$ {sal - desconto:.2f}')
if sal >= 800.01 and sal <= 1200:
desconto = sal * 0.09
print(f'O valor de contribução ao INSS é de {desconto:.2f}\n'
f'Logo seu Salário final é R$ {sal - desconto:.2f}')
if sal >= 1200.01:
desconto = sal * 0.11
print(f'O valor de contribução ao INSS é de {desconto:.2f}\n'
f'Logo seu Salário final é R$ {sal - desconto:.2f}') |
00c404216a2a2f4de4c8fa82c2ae341ce35e6f20 | FredThx/turing | /turing.py | 4,891 | 3.609375 | 4 | '''Une emulation de machine de turing
Exemple : voir siracuse.py
Auteur : fredThx
'''
class Turing:
'''Une machine de T.
'''
droite = 1
R = 1
D = 1
gauche = -1
G = -1
L = -1
b = " "
def __init__(self, etats = None, data = None, start_right = False):
'''
- etats : {1:TEtat(...), 2:...}
- data : [...] ou " 00111"
'''
self.etat = 0
if start_right:
self.indice = len(data)-1
else:
self.indice = 0
i=0
self.data = {}
for c in data or []:
if c == " ":
self.data[i] = None
else:
self.data[i] = c
i += 1
self.etats = etats or {}
def __str__(self):
text=f"Etat : {self.etat+1} => "
for i in range(min(self.indice,min(self.data.keys())), max(self.indice,max(self.data.keys()))+1):
if i == self.indice:
text += f"({self.read(i)})|"
else:
text += f" {self.read(i)} |"
return text
def read(self, indice=None):
'''Lit la case active ou la valeur de l'indice si renseigné'''
if indice is None:
return self.data.get(self.indice, self.b)
else:
return self.data.get(indice, self.b)
def write(self, value):
'''Ecrit value dans la case active'''
if value in [None,self.b]:
del self.data[self.indice]
else:
self.data[self.indice]=value
def move(self, deplacement):
''' Déplace la curseur à droite (+1) ou à gauche (-1)'''
self.indice += deplacement
def set_etat(self, etat):
'''Chaneg d'état '''
self.etat = etat
def run_once(self, verb = True):
result = self.etats[self.etat].do(self)
if verb:
print(self)
return result
def run(self, verb = True):
n=0
if verb:
print(self)
while self.run_once(verb):
n +=1
if verb:
print(f"fin étape {n}")
print(f"Fin du calcul en {n} étapes")
class TEtat:
'''Le code d'un état
'''
def __init__(self, indice, actions = None):
self.indice = indice
self.actions = actions
assert len(self.actions) == len(set(self.actions)), f"Erreur : actions en doublons : {self.actions}"
def do(self, machine):
'''Execute les actions'''
for action in self.actions:
result = action.do(machine)
if result:
return result
def __str__(self):
txt = f"Etat {self.indice} :\n"
for action in self.actions:
txt += f"\t{str(action)}\n"
return txt
class TAction:
'''Une action : Si Lecture X => Ecriture, Déplacement, Etat+1
'''
def __init__(self, lecture, ecriture=None, deplacement=None, etat=None):
self.lecture = str(lecture)
if ecriture is None:
self.ecriture = None
else:
self.ecriture = str(ecriture)
self.deplacement = deplacement
self.etat = etat
def __str__(self):
return f"TAction: {self.lecture}=>{self.ecriture} | {self.deplacement} | {self.etat} "
def do(self, machine):
'''Execute l'action est retourne True si l'action a été réalisée
'''
if machine.read() == self.lecture:
change = False
if self.ecriture:
#print(f"Write {self.ecriture} ({type(self.ecriture)})on {machine}")
machine.write(self.ecriture)
change = True
if self.deplacement:
machine.move(self.deplacement)
change = True
if self.etat:
machine.set_etat(self.etat-1)
change = True
if change:
return True
"""
def xread(self):
if self.etat == 0:
if self.data.get(self.indice) != None:
self.indice += 1
self.etat = 0
else:
self.indice -= 1
self.etat = 1
elif self.etat == 1:
if self.data.get(self.indice) == None:
self.data[self.indice] = 1
self.etat = 3 #terminé
elif self.data.get(self.indice) < "9":
self.data[self.indice] = chr(ord(self.data.get(self.indice)) + 1)
self.indice -=1
self.etat = 2
elif self.data.get(self.indice) == "9":
self.data[self.indice] = 0
self.indice -=1
self.etat = 1
elif self.etat == 2:
if self.data.get(self.indice) != None:
self.indice -=1
self.etat = 2
else:
self.etat = 3 #terminé
"""
|
8d16e63f7eeaf5f9190f4bc3b7d4787e51a43e89 | ichsankurnia/Python-Basic | /list/string.py | 1,722 | 4.1875 | 4 | string = "HeLo PyThOn"
print("string: ", string)
print("string.capitalize()", string.capitalize())
print("string.upper()", string.upper())
print("string.lower()", string.lower())
print("string.casefold()", string.casefold())
print("'hello'.center(11,'-')", "hello".center(11,'-'))
print("string.count(o)", "hello python".count('o'))
print("Ories.encode()", "Ories".encode())
print("string.endswith('n')", string.endswith('n'))
print("string.startwith('H')", string.startswith("H"))
print("string.find('o')", string.find('o'))
print("string.index('o')", string.index('o'))
print("{} {}".format("Hello", "Python"), "\n")
print("string.isalnum()", string.isalnum())
print("string.isalpha()", string.isalpha())
print("12311.isnumeric()", "12311".isnumeric())
print("' '.isspace()", " ".isspace())
print("Hello.istitle()", "Hello".istitle())
print("HELLO.isupper()", "HELLO".isupper(), "\n")
print("'-'.join('hello')", "-".join("hello"))
print("string.replace('p', 'T')", string.replace('T', 'p'))
print("'hello there learner'.rfind('e')", "hello there learner".rfind('e')) # find last position of a specified value
print("'hello there learner'.rindex('e')", "hello there learner".rindex('e')) # find last position of a specified value
print("'hello there hello here'.partion('hello')", "hello there hello here".partition("hello"))
print("'hello there hello here'.rpartion('hello')", "hello there hello here".rpartition("hello"))
print("string.swapecase()", string.swapcase())
print("string.title()", string.title())
print("'Ha He Hi Ho Hu'.translate(str.maketrans('aeiou','12345'))", "Ha He Hi Ho Hu".translate(str.maketrans("aeiou", "12345")))
print("'10'.zfill(5)", "10".zfill(5))
print("string.split()", string.split()) |
5e653af5a3fb799c1cc33e2d0c5a2e8e8c691a57 | clintreyes/num_model | /count_substrings.py | 581 | 3.6875 | 4 | gene = 'AGTCAATGGAATAGGCCAAGCGAATATTTGGGCTACCA'
def freq(letter,text):
j = 0
for i in text:
if(i == letter):
j += 1
return j
print("The frequency of A in string gene is %d" %freq('A',gene))
print("The frequency of C in string gene is %d" %freq('C',gene))
print("The frequency of G in string gene is %d" %freq('G',gene))
def pairs(letter,text):
j = 0
for i in range(len(text)-1):
if(text[i] == letter):
if(text[i+1] == letter):
j += 1
return j
print(pairs('G',gene))
def mystruct(text):
for i in range(len(text)):
if(text[i] == ) |
d8c6337fdac7d51141617fb028d3514118f2160a | srikanthpragada/PYTHON_27_AUG_2020 | /demo/funs/sorted_demo.py | 330 | 3.71875 | 4 | nums = [-10, 10, 20, 5, -50, 1]
names = ['Java', 'javascript', 'python', 'C#', "SQL"]
for n in sorted(nums, key=abs):
print(n, end=' ')
print("\nSorted Names ignoring case")
for n in sorted(names, key=str.upper):
print(n, end=' ')
print("\nSorted Names by length")
for n in sorted(names, key=len):
print(n, end=' ') |
26c10d3b1ac6ccca2beababd253b5a3bd2f297f9 | shishengjia/PythonDemos | /数据分析/read_tab_delimited.py | 1,140 | 3.765625 | 4 | # encoding: utf-8
"""
@author: shishengjia
@time: 2017/10/12 下午12:45
"""
"""
this format can be read in almost the same way as CSV fles,
as the Python module csv supports so-called dialects that
enable us to use the same principles to read variations of
similar fle formats—one of them being the tab delimited format.
"""
import csv
file_name = 'ch02-data.tab'
# data = []
# reader = None
# header = None
#
# try:
# with open(file_name) as f:
# reader = csv.reader(f, dialect=csv.excel_tab)
# header = next(reader)
# data = [row for row in reader]
# except csv.Error as e:
# print(e)
#
# if header:
# print(header)
# print('===========')
#
# for item in data:
# print(item)
file_name_2 = 'ch02-data-dirty.tab'
data = []
reader = None
header = None
try:
with open(file_name) as f:
reader = csv.reader(f, dialect=csv.excel_tab)
header = next(reader)
# 去除制表符
data = [row[0].strip().split('\t') for row in reader]
except csv.Error as e:
print(e)
if header:
print(header)
print('===========')
for item in data:
print(item) |
12c28a5a778a7764b41780b10fbd4324c369688d | Jungeol/algorithm | /leetcode/easy/172_factorial_trailing_zeroes/hsh2438.py | 439 | 3.53125 | 4 | """
https://leetcode.com/problems/factorial-trailing-zeroes/
Runtime: 68 ms, faster than 5.51% of Python3 online submissions for Factorial Trailing Zeroes.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Factorial Trailing Zeroes.
"""
class Solution:
def trailingZeroes(self, n: int) -> int:
count = 0
while n > 0:
count += int(n / 5)
n = n / 5
return count |
92578a4d2ea658a02029df6288200900ba1d402a | RainMoun/python_programming_camp | /day6/session_6.1.py | 2,151 | 3.578125 | 4 | menu_university = {
'浙江': {
'杭州': {
'下沙区': {
'杭州电子科技大学': {},
'浙江工商大学': {},
'浙江理工大学': {}
},
'西湖区': {
'浙江大学': {},
},
},
'宁波': {
'江北区': {
'宁波大学': {}
},
'鄞州区': {
"宁波诺丁汉大学": {}
}
}
}
}
sign_exit = False
while not sign_exit:
menu = menu_university
for key in menu.keys():
print(key)
choose_first = input("第一层:").strip()
if choose_first == 'b':
break
elif choose_first == 'exit':
sign_exit = True
break
elif choose_first in menu:
pass
else:
continue
while not sign_exit:
menu_2 = menu[choose_first]
for key in menu_2.keys():
print(key)
choose_second = input("第二层:").strip()
if choose_second == 'b':
break
elif choose_second == 'exit':
sign_exit = True
break
elif choose_second in menu_2:
pass
else:
continue
while not sign_exit:
menu_3 = menu_2[choose_second]
for key in menu_3.keys():
print(key)
choose_third = input("第三层:").strip()
if choose_third == 'b':
break
elif choose_third == 'exit':
sign_exit = True
break
elif choose_third in menu_3:
pass
else:
continue
while not sign_exit:
menu_4 = menu_3[choose_third]
for key in menu_4.keys():
print(key)
choose_forth = input("第四层:").strip()
if choose_forth == 'b':
break
elif choose_forth == 'exit':
sign_exit = True
break
else:
pass
|
d205c02a95d5c23852a46286401dffdd17a6246e | iphakman/playing_with_python | /exercises/faboulous_fred.py | 621 | 3.5625 | 4 | import random
L = []
R = []
def agregar1():
g = random.randint(1, 9)
L.append(g)
def adivina():
j = input("insert number: ")
R.append(int(j))
agregar1()
total = 0
cnt = 0
guess = 0
while guess == 0:
for a in L:
print("{}".format(a))
cuenta = len(L)
circulo = 0
while circulo < cuenta:
adivina()
if R[circulo] == L[circulo]:
total += 1
else:
guess = 1
circulo = cuenta
circulo += 1
del R
R = []
agregar1()
print("Tu score is: {}".format(total))
for a in L:
print("{}".format(a))
|
4423a39d17bb6e87d9e8cdb3db56ddaac686cf1d | mallireddy09/Python | /Programs/interview.py | 2,192 | 3.921875 | 4 |
1 What is Python?
2 What are the benefits of Python?
3 What are the key features of Python?
4 What type of language is Python? Programming or Scripting?
5 What are the applications of Python?
6 What is the difference between list and tuple in Python?
7 What are the global and local variables in Python?
8 Define PYTHON PATH?
9 What are the two major loop statements?
10 What do you understand by the term PEP 8?
11 How memory management is done in Python?
12 What is the principal difference between Java and Python?
13 Define modules in Python?
14 What are the built-in types available in Python?
15 What are Python Decorators?
16 How do we find bugs and statistical problems in Python?
17 What is the difference between .py and .pyc files?
18 How do you invoke the Python interpreter for interactive use?
19 Define String in Python?
20 What do you understand by the term namespace in Python?
21 How do you create a Python function?
22 Define iterators in Python?
23 How does a function return values?
24 Define slicing in Python?
25 How can Python be an interpreted language?
26 function without return is valid?
27 Define package in Python?
28 How can we make a Python script executable on Unix?
29 Which command is used to delete files in Python?
30 Define pickling and unpickling in Python?
31 Explain the difference between local and global namespaces?
32 What is a boolean in Python?
33 What is Python String format and Python String replace?
34 Name some of the built-in modules in Python?
35 What are the functions in Python?
36 What are Dict and List comprehensions in Python?
37 Define the term lambda?
38 When would you use triple quotes as a delimiter? 39 Define self in Python?
40 What is init?
41. How do you debug a Python program?
42. What is <Yield> Keyword in Python?
43. How to convert a list into a string?
44. How to convert a list into a tuple?
45. How to convert a list into a set?
46. How to count the occurrences of a particular element in the list?
47. What is NumPy array?
48. How can you create Empty NumPy Array In Python?
49. What is a negative index in Python?
50. How do you Concatenate Strings in Python? |
22d8bba70ab69f3ee2c253e273761562f391ebfe | urvashi04/python-task | /prob6.py | 845 | 3.890625 | 4 | #!/usr/bin/python3
#python Program which performs similar operation like "CAT" shell command
choice = int(input("Enter you Choice : \n 1. Cat \t2.Cat -b\t3.Cat -s\t4.Cat -E\n:"))
#OPEN the FILE
file=open("readfile.txt","r")
#Normal Reading like cat function
if choice==1:
print(file.read())
#With -b option
elif choice==2:
i=1
#to print non empty lines
for lines in file:
if lines.strip() !="":
print(str(i)+". " +lines.strip())
i+=1
#With -s option
elif choice==3:
#to suppress empty lines
for lines in file:
if lines.strip() !="":
print(lines.strip())
#with -E option:
elif choice==4:
#to put $ symbol in end of files
for lines in file:
print(lines.strip() +"$")
#if wrong choice
else:
print("Enter choice from given inputs")
file.close()
|
856b39c58639e7f4d3ccf6c518ff6ccf55951bc8 | wiput1999/Python101 | /1 Class 1/Homework/5.py | 260 | 3.609375 | 4 | import math
w = float(input("Weight :"))
h = float(input("Height :"))
M = math.sqrt((w*h)/3600)
D = 71.84*w**0.425*h**0.725/10000
B = 0.0003207*h**0.3*(1000*w)**(0.7285-0.0188**(3+math.log(10,w)))
print("Mosteller :",M)
print("Dubois :",D)
print("Boyd :",B) |
9e2975f5b69458ce9a9e888b756e06de98133169 | digant0705/Algorithm | /LeetCode/Python/389 Find the Difference.py | 1,135 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Find the Difference
===================
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more
letter at a random position.
Find the letter that was added in t.
"""
import collections
class Solution(object):
"""算法思路:
利用hash table记录每个字母出现的次数,最后多出来的那个即为结果
Time: O(n)
Space: O(n)
"""
def findTheDifference(self, s, t):
table = collections.defaultdict(int)
for i in xrange(len(t)):
table[t[i]] += 1
if i < len(s):
table[s[i]] -= 1
return [k for k, v in table.items() if v][0]
class Solution(object):
"""算法思路:
利用异或去重
"""
def findTheDifference(self, s, t):
r = ord(t[-1])
for i in xrange(len(s)):
r ^= ord(s[i])
r ^= ord(t[i])
return chr(r)
s = Solution()
print s.findTheDifference("", "a")
print s.findTheDifference("aaa", "aaaa")
print s.findTheDifference("abcd", "bdace")
|
78c465e7092094239851d7aec9199840f12a068c | anc1revv/coding_practice | /leetcode/medium/single_number.py | 418 | 3.96875 | 4 | '''Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?'''
def single_number(input_array):
for num in input_array:
return rev_string
def main():
input_array = [3,4,3,2,2,4,1,5,1]
print single_number(input_array)
if __name__ == "__main__": main() |
131385104d133e4391a503f0effd9e27a915d03b | jaehyunan11/leetcode_Practice | /rotate_array.py | 1,811 | 3.84375 | 4 | # Input: nums = [1,2,3,4,5,6,7], k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
# Input: nums = [-1,-100,3,99], k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
# class Solution:
# def rotate(self, nums, k):
# n = len(nums)
# k %= n
# self.reverse(nums, 0, len(nums) - 1)
# self.reverse(nums, 0, k-1)
# self.reverse(nums, k, len(nums)-1)
# def reverse(self, arr, start, end):
# while start < end:
# arr[start], arr[end] = arr[end], arr[start]
# start += 1
# end -= 1
# nums = [1, 2, 3, 4, 5, 6, 7]
# k = 3
# s = Solution()
# print(s.rotate(nums, k))
###################################################
# arr = [1, 2, 3, 4, 5]
# k = 2 # k times rotate
# print("Original Array")
# for i in range(0, len(arr)):
# print(arr[i])
# Roate the given array by k times toward left
def rotate(arr, k):
for i in range(0, k):
# store the first element of the array
first = arr[0]
for j in range(0, len(arr)-1):
arr[j] = arr[j+1]
arr[len(arr)-1] = first
return arr
arr = [1, 2, 3, 4, 5]
k = 2 # k times rotate
print(rotate(arr, k))
# for i in range(0, k):
# # store the first element of the array
# temp = arr[0]
# for j in range(0, len(arr) - 1):
# # shift element of array by one
# arr[j] = arr[j+1]
# # last element
# arr[len(arr) - 1] = temp
# print("Array after left rotation: ")
# for i in range(0, len(arr)):
# print(arr[i]),
#######################################################
|
1504208b08ca80d8af779c500850ccf98f524f83 | allenkim/algorithm-work | /UVA/136-UglyNumbers/uglynumbers.py | 675 | 3.546875 | 4 | uglyNumbers = list();
uglyNumbers.append(1);
for i in range(1499):
x = uglyNumbers[0]
uglyNumbers.remove(x)
temp1 = 2*x
temp2 = 3*x
temp3 = 5*x
temp = temp1
j = 0
while j < len(uglyNumbers):
if uglyNumbers[j] > temp :
uglyNumbers.insert(j, temp)
elif uglyNumbers[j] < temp :
j += 1
continue
if temp == temp1:
temp = temp2
elif temp == temp2:
temp = temp3
else:
break
j += 1
if temp == temp1:
uglyNumbers.append(temp)
temp = temp2
if temp == temp2:
uglyNumbers.append(temp)
temp = temp3
if temp == temp3:
uglyNumbers.append(temp)
print uglyNumbers
ans = uglyNumbers[0]
print "The 1500'th ugly number is %d" % ans
|
cd565f682f43ed2859068fc76ce3b92af67a9819 | chin8628/Pre-Pro-IT-Lardkrabang-2558 | /Prepro-Onsite/W1_D3_Salary.py | 488 | 3.703125 | 4 | """ W1_D3_Salary """
def main(salary, addition):
""" this is function """
if salary >= 50000.01:
addition = 0.04
elif salary >= 25000.01:
addition = 0.07
elif salary >= 15000.01:
addition = 0.10
elif salary >= 7000.01:
addition = 0.12
else:
addition = 0.15
print("%.2f" % float(salary + (salary * addition)))
print("%.2f" % float(salary * addition))
print(str(int(addition * 100)) + "%")
main(float(input()), 0)
|
ca4149f385a7ff762da411ab7b033541d02d2e42 | Jian-jobs/leetcode-notes | /solutions/240.py | 797 | 3.640625 | 4 | """
{
"author": "Yucheng Huang",
"difficulty": "medium",
"link": "https://leetcode.com/problems/search-a-2d-matrix-ii/description/",
"beats": 0.1394,
"category": ["array"],
"tags": ["BST"],
"questions": []
}
"""
"""
思路
- 从右上角开始,类似BST的搜索
"""
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
m, n = len(matrix), len(matrix[0])
i,j = 0,n-1
while i<m and j>=0:
if matrix[i][j] > target:
j -= 1
elif matrix[i][j] < target:
i += 1
else:
return True
return False |
0f087446e76772475cbe1b2d2872454dfa24bcfc | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/schmat029/util.py | 2,420 | 3.65625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose: creates grid functions for 2048
#
# Author: Matthias
#
# Created: 27-04-2014
# Copyright: (c) Matthias 2014
# Licence: <your licence>
#-------------------------------------------------------------------------------
def create_grid(grid):
for i in range(4):
# add a new empty list into grid
grid.append([])
for j in range(4):
# add 0, 0, 0, 0 into this newly created sublist
grid[i].append(0)
return grid
def print_grid(grid):
# print top border
print("+" + "-"*20 + "+")
for row in range(4):
# print left border
print("|", end="")
for value in grid[row]:
# only print non-zero values
if value == 0:
print(" " * 5, end="")
else:
print("{0:<5}".format(value), end="")
# print right border
print("|")
# print bottom border
print("+" + "-"*20 + "+")
def check_lost(grid):
# check vor zero values
for row in range(4):
for value in grid[row]:
if value == 0:
return False
# check for adjacent equal values
for row in range(3):
for column in range(3):
# horizontally adjacent
if grid[row][column] == grid[row][column + 1]:
return False
# vertically adjacent
if grid[row][column] == grid[row + 1][column]:
return False
return True
def check_won(grid):
for row in range(4):
for value in grid[row]:
# check if any one value is more or equal to 32
if value >= 32:
return True
return False
def copy_grid(grid):
new_grid = []
for row in range(4):
# add a new row
new_grid.append([])
for value in grid[row]:
# copy each value into this newly created row
new_grid[row].append(value)
return new_grid
def grid_equal(grid1, grid2):
for row in range(4):
for column in range(4):
# check if each value in grid1 is equal to the equivalent value in grid2
if grid1[row][column] != grid2[row][column]:
return False
return True
|
f417f3f1a7944249510d327fa307ac395f80d02c | llimllib/personal_code | /javascript/bitofphysics/data.py | 23,272 | 3.578125 | 4 | [
{"name": "lastbounce",
"title": "Last Bounce",
"explain_before": """Storing dx and dy as values is a way of saying which way
we are going. This can be done in other ways. the changes here use lastx and
lasty to calculate dx and dy. lastx,lasty simply says where we were last time.
The essential difference with the two forms is that dx and dy says what
direction the ball is moving, whereas using lastx and lasty changes that to say
"move the ball in the same direction as last time".
<p>dx and dy can still be calculated as needed, but the important thing is that
dx and dy don't need to be stored. I bet you're wondering why you'd want to
change to this way. read on...""",
"code": """var lastx = x - dx;
var lasty = y - dy;
function draw() {
clear();
circle(x, y, 10);
dx = x - lastx;
dy = y - lasty;
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
lastx=x;
lasty=y;
x += dx;
y += dy;
}
init();""",
"explain_after": """Try to change the draw() function so that the ball
accelerates or decelerates every time it hits a wall.""",
"library": """var x = 150;
var y = 150;
var dx = 2;
var dy = 4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
} """
},
{"name": "gravity",
"title": "Gravity",
"explain_before": """Here's a small change to make a bouncing ball. When dy is
calculated we add a little bit extrea to it for gravity. If you let the ball
bounce for a while you'll see that the ball starts bouncing more and more. In
this example there is no friction or wind resistance. This allows tiny errors
to addd up over time to become significant effects""",
"code": """var GRAVITY = 0.2;
function draw() {
clear();
circle(x, y, 10);
var dx = x - lastx;
var dy = (y - lasty)+GRAVITY;
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
lastx=x;
lasty=y;
x += dx;
y += dy;
}
init(); """,
"explain_after": """Add the lines dx*=0.999; and dy*=0.999; to see what
happens. This makes the x and y speed 99.9% of its previous value. That's like
a little bit of air resistance.""",
"library": """var x = 150;
var y = 150;
var lastx = x - 2;
var lasty = y - 4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
} """
},
{"name": "moreballs",
"title": "More Balls",
"explain_before": """ If we are going to have more than one ball we'll need
more variables. We could do this by adding x2,y2 lastx2, lasty2 but if we
wanted to have more than a few balls, things would get very messy. a tidier way
would be to use an object to hold all the values for each ball. we can do this
with the line<br><code>var ball2 = new Object;</code>
<p>This code makes a new object called ball2 and gives it x ,y ,lastx and lasty
values. a cirlce is drawn at ball2.x, ball2.y but it doesn't move yet.""",
"code": """var ball2 = new Object;
ball2.x=100;
ball2.y=100;
ball2.lastx=100-2;
ball2.lasty=100-1;
function draw() {
clear();
circle(x, y, 10);
circle(ball2.x,ball2.y,5);
var dx = x - lastx;
var dy = (y - lasty)+GRAVITY;
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
lastx=x;
lasty=y;
x += dx;
y += dy;
}
init(); """,
"explain_after": """try changing x , y, lastx, lasty to use a ball1.x,
ball1.y, ball1.lastx, ball1.lasty""",
"library": """var x = 150;
var y = 150;
var lastx = x - 2;
var lasty = y - 4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
var GRAVITY = 0.2;
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
}"""
},
{"name": "movefunction",
"title": "Ball Movement",
"explain_before": """ Because all of the values of ball2 were attached to a
single object, it is easy to refer to all of the values of the ball together.
The code below adds a new function called moveBall The code in the function is
exactly the same as the code for bouncing the ball from earlier, only it
applies to the x, y, lastx, and lasty values of whatever is passed to the
function as a parameter. If you call moveBall(ball1) it will apply to ball1, if
you call moveBall(ball3) it will apply to ball3.
<p>After ball movment has been moved to a seperate function you will see the
draw() function is quite tidy, it clears, moves 4 balls and draws 4 circles.
Nothing could be simpler. Until.... """,
"code": """var ball1 = new Object;
ball1.x=150;
ball1.y=150;
ball1.lastx=150-2;
ball1.lasty=150-4;
var ball2 = new Object;
ball2.x=100;
ball2.y=100;
ball2.lastx=100-2;
ball2.lasty=100-1;
var ball3 = new Object;
ball3.x=150;
ball3.y=100;
ball3.lastx=150+1;
ball3.lasty=100-3;
var ball4 = new Object;
ball4.x=100;
ball4.y=150;
ball4.lastx=100+2;
ball4.lasty=150+4;
function moveBall(ball) {
var dx = ball.x - ball.lastx;
var dy = (ball.y - ball.lasty)+GRAVITY;
if (ball.x + dx > WIDTH || ball.x + dx < 0)
dx = -dx;
if (ball.y + dy > HEIGHT || ball.y + dy < 0)
dy = -dy;
ball.lastx=ball.x;
ball.lasty=ball.y;
ball.x += dx;
ball.y += dy;
}
function draw() {
clear();
moveBall(ball1);
moveBall(ball2);
moveBall(ball3);
moveBall(ball4);
circle(ball1.x,ball1.y,5);
circle(ball2.x,ball2.y,5);
circle(ball3.x,ball3.y,5);
circle(ball4.x,ball4.y,5);
}
init();""",
"explain_after": """
""",
"library": """var x = 150;
var y = 150;
var lastx = x - 2;
var lasty = y - 4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
var GRAVITY = 0.2;
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
} """
},
{"name": "constraints",
"title": "Constraints",
"explain_before": """<p>The four balls in the previous example started in a
square, but they were all moving in different directions, so they seperated
quickly. What would happen if you bound them together so they couldn't leave
each other? We can try this by pushing and pulling the balls. If they get too
far apart then push them together. If they get too close, push them apart.
<p>For starters to do this, it would be useful to know how far apart they are and
how far apart you want them. The first part of this is easy if you listened at
school. Repeat after me... <em>"the square of the hypotenuse is equal to the sum of
the squares of the other two sides"</em>.
<p>better yet, how about
<p><code>distance * distance = Xdifference * Xdifference + Ydifference +
yDifference;</code>
<p>The second value, what distance should they be, is much easier. Whatever it was
when we started. The function to constrain the balls to a desired distance is
actually fairly simple. The balls move in opposite directions to each other
(either closer together of further apart). and each ball moves half the
distance of what is needed to do the correction.
<p>in the code below ball1 and ball2 are constrained to stay at a distance of
70.71, ball3 and ball4 are also constrained the same amount. We're also drawing
a line between the balls just to see where that constraint is.""",
"code": """function constrain(ballA,ballB,desiredDistance) {
var dx = ballA.x-ballB.x;
var dy = ballA.y-ballB.y;
var distancesquared = dx*dx + dy*dy;
var distance = Math.sqrt(distancesquared);
var CorrectionRequired = desiredDistance-distance;
dx = (dx / distance) * (CorrectionRequired / 2)
dy = (dy / distance) * (CorrectionRequired / 2)
shoveBall(ballA,dx,dy);
shoveBall(ballB,-dx,-dy);
}
function shoveBall(ball,dx,dy) {
if (ball.x + dx > WIDTH || ball.x + dx < 0)
dx = -dx;
if (ball.y + dy > HEIGHT || ball.y + dy < 0)
dy = -dy;
ball.x+=dx;
ball.y+=dy;
}
function moveBall(ball) {
var dx = ball.x - ball.lastx;
var dy = (ball.y - ball.lasty)+GRAVITY;
if (ball.x + dx > WIDTH || ball.x + dx < 0)
dx = -dx;
if (ball.y + dy > HEIGHT || ball.y + dy < 0)
dy = -dy;
ball.lastx=ball.x;
ball.lasty=ball.y;
ball.x += dx;
ball.y += dy;
}
function draw() {
clear();
moveBall(ball1);
moveBall(ball2);
moveBall(ball3);
moveBall(ball4);
constrain(ball1,ball2, 70.71);
line(ball1.x,ball1.y,ball2.x,ball2.y);
constrain(ball3,ball4, 70.71);
line(ball3.x,ball3.y,ball4.x,ball4.y);
circle(ball1.x,ball1.y,5);
circle(ball2.x,ball2.y,5);
circle(ball3.x,ball3.y,5);
circle(ball4.x,ball4.y,5);
}
init(); """,
"explain_after": """ It looks like a couple of sticks. What happens when you
constrain ball2 to ball3? It should link them all together like a chain. use a
constrain(ball2,ball3, 50); Don't forget to draw a line so you can see the
connection
<p>if you are wondering why the length is 50 instead of 70 for the other two, it
is because the first two constraints we made connected the diagonals of the
square. so they started 70.71 apart ball2 and ball3 start at a distance of 50
from each other.""",
"library": """var ball1 = new Object;
ball1.x=150;
ball1.y=150;
ball1.lastx=150-2;
ball1.lasty=150-4;
var ball2 = new Object;
ball2.x=100;
ball2.y=100;
ball2.lastx=100-2;
ball2.lasty=100-1;
var ball3 = new Object;
ball3.x=150;
ball3.y=100;
ball3.lastx=150+1;
ball3.lasty=100-3;
var ball4 = new Object;
ball4.x=100;
ball4.y=150;
ball4.lastx=100+2;
ball4.lasty=150+4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
var GRAVITY = 0.1;
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function line(x1,y1,x2,y2) {
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
}"""
},
{"name": "box",
"title": "Box",
"explain_before": """This code has connectred all four balls up using six
constraints. Two diagonals and four around the border. If we removed the
diagonal constraints the edges would be all the right length but the shape
would fold up like a cardboard box.""",
"code": """function moveBall(ball) {
var dx = ball.x - ball.lastx;
var dy = (ball.y - ball.lasty)+GRAVITY;
if (ball.x + dx > WIDTH || ball.x + dx < 0)
dx = -dx;
if (ball.y + dy > HEIGHT || ball.y + dy < 0)
dy = -dy;
ball.lastx=ball.x;
ball.lasty=ball.y;
ball.x += dx;
ball.y += dy;
}
function draw() {
clear();
moveBall(ball1);
moveBall(ball2);
moveBall(ball3);
moveBall(ball4);
constrain(ball1,ball2, 70.71);
line(ball1.x,ball1.y,ball2.x,ball2.y);
constrain(ball3,ball4, 70.71);
line(ball3.x,ball3.y,ball4.x,ball4.y);
constrain(ball2,ball3, 50);
line(ball2.x,ball2.y,ball3.x,ball3.y);
constrain(ball1,ball3, 50);
line(ball1.x,ball1.y,ball3.x,ball3.y);
constrain(ball2,ball4, 50);
line(ball2.x,ball2.y,ball4.x,ball4.y);
constrain(ball1,ball4, 50);
line(ball1.x,ball1.y,ball4.x,ball4.y);
circle(ball1.x,ball1.y,5);
circle(ball2.x,ball2.y,5);
circle(ball3.x,ball3.y,5);
circle(ball4.x,ball4.y,5);
}
init();""",
"explain_after": """ It's a box and it stays in shape, even while spinning, it
doesn't look quite right when it hits things though. Next up, we'll refine the
move function to refine the collision with the walls and floor.""",
"library": """var ball1 = new Object;
ball1.x=150;
ball1.y=150;
ball1.lastx=150-2;
ball1.lasty=150-4;
var ball2 = new Object;
ball2.x=100;
ball2.y=100;
ball2.lastx=100-2;
ball2.lasty=100-1;
var ball3 = new Object;
ball3.x=150;
ball3.y=100;
ball3.lastx=150+1;
ball3.lasty=100-3;
var ball4 = new Object;
ball4.x=100;
ball4.y=150;
ball4.lastx=100+2;
ball4.lasty=150+4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
var GRAVITY = 0.1;
function constrain(ballA,ballB,desiredDistance) {
var dx = ballA.x-ballB.x;
var dy = ballA.y-ballB.y;
var distancesquared = dx*dx + dy*dy;
var distance = Math.sqrt(distancesquared);
var CorrectionRequired = desiredDistance-distance;
dx = (dx / distance) * (CorrectionRequired / 2)
dy = (dy / distance) * (CorrectionRequired / 2)
shoveBall(ballA,dx,dy);
shoveBall(ballB,-dx,-dy);
}
function shoveBall(ball,dx,dy) {
if (ball.x + dx > WIDTH || ball.x + dx < 0)
dx = -dx;
if (ball.y + dy > HEIGHT || ball.y + dy < 0)
dy = -dy;
ball.x+=dx;
ball.y+=dy;
}
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function line(x1,y1,x2,y2) {
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
}"""
},
{"name": "betterbounce",
"title": "Better Bounce",
"explain_before": """ The bouncing used from the original example with a single
ball was quite simple. It checked to see if the ball would be out of bounds on
the next movement and if so, it would change direction and go the other way.
That's good enough for a simple object but to make the box bounce look more
realistic it really needs to be a bit better.
<p>Instead of just changing the direction, a more precise approach would be to
check how far into the edge the ball was going to penetrate and bounce back by
that amount. At the same time a minor tweak to the lastx/lasty can be done to
act as if the ball had come from the other side of the barrier.""",
"code": """function moveBall(ball) {
var dx = ball.x - ball.lastx;
var dy = (ball.y - ball.lasty)+GRAVITY;
var penetration
ball.lasty=ball.y;
ball.lastx=ball.x;
if (dy > 0) {
penetration = (ball.y+dy) - HEIGHT;
if (penetration > 0) {
ball.lasty = HEIGHT + (HEIGHT-ball.lasty)
ball.y = HEIGHT-penetration;
dx*=0.9;
} else ball.y += dy;
} else {
penetration = 0 - (ball.y+dy);
if (penetration > 0) {
ball.lasty = 0 + (0-ball.lasty)
ball.y = 0+penetration;
dx*=0.9;
} else ball.y += dy;
}
if (dx > 0) {
penetration = (ball.x+dx) - WIDTH;
if (penetration > 0) {
ball.lastx = WIDTH + (WIDTH-ball.lastx)
ball.x = WIDTH-penetration;
} else ball.x += dx;
} else {
penetration = 0 - (ball.x+dx);
if (penetration > 0) {
ball.lastx = 0 + (0-ball.lastx)
ball.x = 0+penetration;
} else ball.x += dx;
}
}
function draw() {
clear();
moveBall(ball1);
moveBall(ball2);
moveBall(ball3);
moveBall(ball4);
constrain(ball1,ball2, 70.71);
line(ball1.x,ball1.y,ball2.x,ball2.y);
constrain(ball3,ball4, 70.71);
line(ball3.x,ball3.y,ball4.x,ball4.y);
constrain(ball2,ball3, 50);
line(ball2.x,ball2.y,ball3.x,ball3.y);
constrain(ball1,ball3, 50);
line(ball1.x,ball1.y,ball3.x,ball3.y);
constrain(ball2,ball4, 50);
line(ball2.x,ball2.y,ball4.x,ball4.y);
constrain(ball1,ball4, 50);
line(ball1.x,ball1.y,ball4.x,ball4.y);
circle(ball1.x,ball1.y,5);
circle(ball2.x,ball2.y,5);
circle(ball3.x,ball3.y,5);
circle(ball4.x,ball4.y,5);
}
init();""",
"explain_after": """the new move function initially appears much more complex,
but most of that is because there are four seperate checks instead of two
previously. calculating the edge pentration needs to be done for all four sides
seperately. Up until now the code had been using only one check for top/bottom
and one for left/right.
<p>In addition to the new bouncing, there is one other little tweak. When a
collision occurs against the wall or ceiling there is dx*=1/(1+penetration);.
That is a little bit of a friction hack. x motion slows a bit when it hits the
floor or ceiling. Most collisions are with the floor when you have gravity,
this stops them sliding all over the place. calculation of 1/(1+penetration)
equals 1 for no penetration and decreases as the penetration increases.""",
"library": """var ball1 = new Object;
ball1.x=150;
ball1.y=150;
ball1.lastx=150+2;
ball1.lasty=150+4;
var ball2 = new Object;
ball2.x=100;
ball2.y=100;
ball2.lastx=100+2;
ball2.lasty=100+1;
var ball3 = new Object;
ball3.x=150;
ball3.y=100;
ball3.lastx=150+1;
ball3.lasty=100+3;
var ball4 = new Object;
ball4.x=100;
ball4.y=150;
ball4.lastx=100+2;
ball4.lasty=150+4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
var GRAVITY = 0.05
function constrain(ballA,ballB,desiredDistance) {
var dx = ballA.x-ballB.x;
var dy = ballA.y-ballB.y;
var distancesquared = dx*dx + dy*dy;
var distance = Math.sqrt(distancesquared);
var CorrectionRequired = desiredDistance-distance;
dx = (dx / distance) * (CorrectionRequired / 2)
dy = (dy / distance) * (CorrectionRequired / 2)
shoveBall(ballA,dx,dy);
shoveBall(ballB,-dx,-dy);
}
function shoveBall(ball,dx,dy) {
if (ball.x + dx > WIDTH || ball.x + dx < 0)
dx = -dx;
if (ball.y + dy > HEIGHT || ball.y + dy < 0)
dy = -dy;
ball.x+=dx;
ball.y+=dy;
}
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function line(x1,y1,x2,y2) {
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
}"""
},
{"name": "justthebox",
"title": "Finishing Touches",
"explain_before": """Finally, a little bit of tidyup. The circles and diagonal
lines have been removed. This leaves us with just the box outline. In addition
the motion of the box had been randomised at the start so that you can keep
clicking 'run code' and it'll show you a different bounce each time.""",
"code": """function draw() {
clear();
moveBall(ball1);
moveBall(ball2);
moveBall(ball3);
moveBall(ball4);
constrain(ball1,ball2, 70.71);
constrain(ball3,ball4, 70.71);
constrain(ball2,ball3, 50);
line(ball2.x,ball2.y,ball3.x,ball3.y);
constrain(ball1,ball3, 50);
line(ball1.x,ball1.y,ball3.x,ball3.y);
constrain(ball2,ball4, 50);
line(ball2.x,ball2.y,ball4.x,ball4.y);
constrain(ball1,ball4, 50);
line(ball1.x,ball1.y,ball4.x,ball4.y);
}
init();""",
"explain_after": """ Of course there is more to a physics engine than this.
this code gives you one object. If you had two boxes they would not interact
with each other. In addition to this, many physics engines have data stuctures
to aid in eliminating as many collision checks as possible, Most such
optimisations are not part of the physical behaviour itself, they are just
ways to make it run faster.
Nevertheless the fundimentals of the system are here. Adding object interaction
is just a matter of detecting the points that were going to cause a collision
and moving them accordingly. both the detection and the response are more
complicated than a flat wall or floor, but ultimately it comes down to shoving
a few points around. Bouncing and spinning are just natural byproducts of the
shoving.""",
"library": """var ball1 = new Object;
ball1.x=150;
ball1.y=150;
ball1.lastx=150+Math.random()*4.0-2;
ball1.lasty=150+Math.random()*8.0;
var ball2 = new Object;
ball2.x=100;
ball2.y=100;
ball2.lastx=100+Math.random()*4.0-2;
ball2.lasty=100+Math.random()*8.0;
var ball3 = new Object;
ball3.x=150;
ball3.y=100;
ball3.lastx=150+Math.random()*4.0-2;
ball3.lasty=100+Math.random()*8.0;
var ball4 = new Object;
ball4.x=100;
ball4.y=150;
ball4.lastx=100+Math.random()*4.0-2;
ball4.lasty=150+Math.random()*8.0;
ball4.lasty=150+4;
var ctx;
var WIDTH = $("#canvas").width()
var HEIGHT = $("#canvas").height()
var GRAVITY = 0.05
function constrain(ballA,ballB,desiredDistance) {
var dx = ballA.x-ballB.x;
var dy = ballA.y-ballB.y;
var distancesquared = dx*dx + dy*dy;
var distance = Math.sqrt(distancesquared);
var CorrectionRequired = desiredDistance-distance;
dx = (dx / distance) * (CorrectionRequired / 2)
dy = (dy / distance) * (CorrectionRequired / 2)
shoveBall(ballA,dx,dy);
shoveBall(ballB,-dx,-dy);
}
function shoveBall(ball,dx,dy) {
if (ball.x + dx > WIDTH || ball.x + dx < 0)
dx = -dx;
if (ball.y + dy > HEIGHT || ball.y + dy < 0)
dy = -dy;
ball.x+=dx;
ball.y+=dy;
}
function moveBall(ball) {
var dx = ball.x - ball.lastx;
var dy = (ball.y - ball.lasty)+GRAVITY;
var penetration
ball.lasty=ball.y;
ball.lastx=ball.x;
if (dy > 0) {
penetration = (ball.y+dy) - HEIGHT;
if (penetration > 0) {
ball.lasty = HEIGHT + (HEIGHT-ball.lasty)
ball.y = HEIGHT-penetration;
dx*=0.9;
} else ball.y += dy;
} else {
penetration = 0 - (ball.y+dy);
if (penetration > 0) {
ball.lasty = 0 + (0-ball.lasty)
ball.y = 0+penetration;
dx*=0.9;
} else ball.y += dy;
}
if (dx > 0) {
penetration = (ball.x+dx) - WIDTH;
if (penetration > 0) {
ball.lastx = WIDTH + (WIDTH-ball.lastx)
ball.x = WIDTH-penetration;
} else ball.x += dx;
} else {
penetration = 0 - (ball.x+dx);
if (penetration > 0) {
ball.lastx = 0 + (0-ball.lastx)
ball.x = 0+penetration;
} else ball.x += dx;
}
}
function circle(x,y,r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function line(x1,y1,x2,y2) {
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
ctx = $('#canvas')[0].getContext("2d");
return setInterval(draw, 10);
}"""
},
]
|
57a8102a0fbde9a2ebb592a4dc77a1a55c2db5bc | viphiter/pythonStudy | /demo1/test01.py | 337 | 3.71875 | 4 |
class Person(object):
def __init__(self,name,age):
print('自动构造对象',self)
self.name = name
self.age = age
def show(self):
print(f'姓名为:{self.name},年龄为:{self.age}')
def __del__(self):
print('对象销毁',self)
p = Person('苏大强','64')
p.show()
del p |
3064d072d30a61881997be0cfba155a6867d6426 | lennertjansen/dataprocessing | /Homework/Week3/convertCSV2JSON.py | 465 | 3.609375 | 4 | # Convert CSV to JSON
import csv
import pandas
import json
# open csv file and create and open json file
csvfile = open('2016_top19.csv', 'r')
jsonfile = open('2016_top19.json', 'w')
# specify the fieldnames of the columns of interest
fieldnames = ("Country", "gdp_per_capita")
# read into new json file and write the key value pairs per row
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write(',\n')
|
2bacece6b82e5e442d68e9c4b5b8f42e817d104f | JianboTang/a2c | /a2c.py | 2,500 | 3.5625 | 4 | # -*- coding: utf-8 -*-
""" Convert to Chinese numerals """
# Define exceptions
class NotIntegerError(Exception):
pass
def to_chinese(number):
""" convert integer to Chinese numeral """
chinese_numeral_dict = {
'0': '零',
'1': '一',
'2': '二',
'3': '三',
'4': '四',
'5': '五',
'6': '六',
'7': '七',
'8': '八',
'9': '九'
}
chinese_unit_map = [('', '十', '百', '千'),
('万', '十万', '百万', '千万'),
('亿', '十亿', '百亿', '千亿'),
('兆', '十兆', '百兆', '千兆'),
('吉', '十吉', '百吉', '千吉')]
chinese_unit_sep = ['万', '亿', '兆', '吉']
reversed_n_string = reversed(str(number))
result_lst = []
unit = 0
for integer in reversed_n_string:
if integer is not '0':
result_lst.append(chinese_unit_map[unit // 4][unit % 4])
result_lst.append(chinese_numeral_dict[integer])
unit += 1
else:
if result_lst and result_lst[-1] != '零':
result_lst.append('零')
unit += 1
result_lst.reverse()
# clean convert result, make it more natural
if result_lst[-1] is '零':
result_lst.pop()
result_lst = list(''.join(result_lst))
for unit_sep in chinese_unit_sep:
flag = result_lst.count(unit_sep)
while flag > 1:
result_lst.pop(result_lst.index(unit_sep))
flag -= 1
'''
length = len(str(number))
if 4 < length <= 8:
flag = result_lst.count('万')
while flag > 1:
result_lst.pop(result_lst.index('万'))
flag -= 1
elif 8 < length <= 12:
flag = result_lst.count('亿')
while flag > 1:
result_lst.pop(result_lst.index('亿'))
flag -= 1
elif 12 < length <= 16:
flag = result_lst.count('兆')
while flag > 1:
result_lst.pop(result_lst.index('兆'))
flag -= 1
elif 16 < length <= 20:
flag = result_lst.count('吉')
while flag > 1:
result_lst.pop(result_lst.index('吉'))
flag -= 1
'''
return ''.join(result_lst)
if __name__ == '__main__':
foo = ''
for i in range(1, 100001):
foo += to_chinese(i) + '\n'
print(foo)
# print('对不起,第{0}遍'.format(to_chinese(i)))
|
252151be7bff8f1a086aa320a8c179b316b576b9 | SergiBaucells/DAM_MP10_2017-18 | /Tasca_1_Python/src/exercici_2_python.py | 565 | 3.859375 | 4 | def calcula_qualificacio(puntuacio):
if puntuacio > 1.0:
resultat = "Ha de ser entre 0.0 i 1.0!!!"
elif puntuacio >= 0.9:
resultat = "Excel·lent"
elif puntuacio >= 0.8:
resultat = "Notable"
elif puntuacio >= 0.7:
resultat = "Bé"
elif puntuacio >= 0.6:
resultat = "Suficient"
else:
resultat = "Insuficient"
return resultat
print("Introdueix un valor entre 0.0 i 1.0")
while True:
puntuacio = float(input("Introdueix puntuació: "))
print(calcula_qualificacio(puntuacio)) |
ee347129aca4f85feadf7d652a9f18aabaaa0d2b | drgmzgb/Python-Advanced- | /#2 Tuples and Sets/Py Adv 2L2 Average Student Grades.py | 682 | 3.984375 | 4 | # Py Adv 2L2 Average Student Grades - using dictionaries, average
# input / 4
# Scott 4.50
# Ted 3.00
# Scott 5.00
# Ted 3.66
# output / Ted -> 3.00 3.66 (avg: 3.33)
# Scott -> 4.50 5.00 (avg: 4.75)
grades = int(input())
res = {}
for n in range(grades):
name, grade = input().split()
if name not in res:
res[name] = []
res[name].append(f'{(float(grade)):.2f}')
# {'Peter': [5.2, 3.2], 'Mark': [5.5, 2.5, 3.46], 'Alex': [2.0, 3.0]}
for name, grade in res.items():
their_sum = 0
for each_grade in grade:
their_sum += float(each_grade)
avg = f"{their_sum / len(grade):.2f}"
print(f'{name} -> {(" ".join(map(str, grade)))} (avg: {avg})') |
bab0914cec7c850bcc9e28e64cfb56b6cda86867 | cddas/python27-practice | /exercise-1.py | 479 | 4.09375 | 4 | import time
name, age = raw_input("Give me your name and age: ").split(" ")
years_to_centenary = 100 - int(age)
current_year = time.strftime("%Y")
current_year = int(current_year)
message = "Hi " + name + ". You will turn 100 years in the year - " + str( current_year + years_to_centenary )
repeat_times = raw_input("Enter the times you want to see the welcome message : ")
repeat_times = int(repeat_times)
for times in range(repeat_times):
print message
|
1534e6f44547a52966ba3655305444554e607fc5 | agonzalez777/Sphero-BB8-Phone-Home | /spheroBB8_phone_home.py | 5,658 | 3.8125 | 4 | import urllib2
import requests
from datetime import datetime
import json
from math import radians, cos, sin, atan2, degrees, asin, sqrt
import time
import sys
import BB8_driver
import pytz
iss_pass_url = "http://api.open-notify.org/iss-pass.json"
iss_now_url = "http://api.open-notify.org/iss-now.json"
def calculate_initial_compass_bearing(pointA, pointB):
"""
Code From: https://gist.github.com/jeromer/2005586#file-compassbearing-py
Calculates the bearing between two points.
:Parameters:
- `pointA: The tuple representing the latitude/longitude for the
first point. Latitude and longitude must be in decimal degrees
- `pointB: The tuple representing the latitude/longitude for the
second point. Latitude and longitude must be in decimal degrees
:Returns:
The bearing in degrees
:Returns Type:
float
"""
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = radians(pointA[0])
lat2 = radians(pointB[0])
diffLong = radians(pointB[1] - pointA[1])
x = sin(diffLong) * cos(lat2)
y = (cos(lat1) * sin(lat2)) - ((sin(lat1)
* cos(lat2) * cos(diffLong)))
initial_bearing = atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180 to +180 which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# 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))
km = 6367 * c
return km * 0.621371
def nextPass(lat,long):
# Returns the number of seconds till the ISS will next pass a given lat,long
response = requests.get(iss_pass_url, params={'lat': lat, 'lon': long}).json()
if 'response' in response:
dur = response['response'][0]['duration']
pass_datetime = datetime.fromtimestamp(response['response'][0]['risetime'], tz=pytz.utc)
print dur
return [((pass_datetime - datetime.now(tz=pytz.utc)).total_seconds()), dur]
def distanceAndBearingToISS(lat,long):
# Returns the number of miles between the ISS's Lat/Long and a given lat long
obj = json.loads(urllib2.urlopen(iss_now_url).read().decode('utf8'))
iss_lat = obj['iss_position']['latitude']
iss_long = obj['iss_position']['longitude']
return [haversine(float(long), float(lat), float(iss_long), float(iss_lat)), int(calculate_initial_compass_bearing((lat,long),(float(iss_lat),float(iss_long))))]
if __name__ == "__main__":
if len(sys.argv) < 4:
print "Incorrect Number of Parameters: Require [BB-8 MAC Address] [Current_Lat] [Current_Long]"
sys.exit(1)
current_lat = float(sys.argv[2])
current_long = float(sys.argv[3])
bb8 = BB8_driver.Sphero(deviceAddress=sys.argv[1])
bb8.connect()
# Set Current Heading (Should be pointed due north)
bb8.set_heading(0,False)
duration_end = 0
while True:
try:
print('{} seconds left till next pass!'.format(nextPass(current_lat,current_long)[0]))
[distance,bearing] = distanceAndBearingToISS(current_lat,current_long)
print "Distance from BB-8", distance, "and bearing", bearing
# Move BB-8 Head towards that heading
bb8.roll(0, int(bearing),0,False)
if (time.time() <= duration_end):
bb8.set_rgb_led(255, 0, 0, 0, False)
# print ("RED - rgb (255,0,0)", distance)
elif (distance > 10375):
bb8.set_rgb_led(255, 0, 255, 0, False)
#print ("VIOLET - rgb(238,130,238)", distance)
elif (distance <= 10375 and distance > 8300):
bb8.set_rgb_led(0, 0, 255, 0, False)
#print ("BLUE - rgb(0,0,255)", distance)
elif (distance <= 8300 and distance > 6225):
bb8.set_rgb_led(0, 255, 0, 0, False)
#print ("GREEN - rgb (0,255,0)", distance)
elif (distance <= 6225 and distance > 4150):
bb8.set_rgb_led(255, 255, 0, 0, False)
#print ("YELLOW - rgb (255,255,0)", distance)
else:
bb8.set_rgb_led(255, 165, 0, 0, False)
#print ("ORANGE - rgb (255,165,0)", distance)
#BB-8 flashes when it is less then 2 minutes before pass time
[seconds,duration] = nextPass(current_lat, current_long)
if (seconds > 0 and seconds < 120):
t_end = time.time() + seconds
while time.time() < t_end:
bb8.set_rgb_led(255, 0, 255, 0, False)
bb8.set_rgb_led(0, 0, 255, 0, False)
bb8.set_rgb_led(0, 255, 0, 0, False)
bb8.set_rgb_led(255, 255, 0, 0, False)
bb8.set_rgb_led(255, 0, 255, 0, False)
bb8.set_rgb_led(255, 165, 0, 0, False)
bb8.set_rgb_led(255, 0, 0, 0, False)
duration_end = time.time() + duration
time.sleep(5)
except KeyboardInterrupt:
bb8.disconnect()
sys.exit(0)
|
e26ed640de1c229f0592a5489998371b8544bcb0 | quinnajames/lexcheck | /lexcheck.py | 1,464 | 3.578125 | 4 | import sys
from collections import defaultdict
def alphagramify(word):
alphagram = ''.join(sorted(list(word)))
return alphagram
def find_typos(list_of_lists):
typo_lines = []
for num, answers in enumerate(list_of_lists,start=1):
if answers == None:
typo_lines.append(num)
return typo_lines
def setup(lexicon, wordfile):
with open(lexicon, 'r') as f:
lexlist = [line.rstrip() for line in f]
alphagram_list = [alphagramify(word) for word in lexlist]
alphagram_dict = dict(zip(lexlist, alphagram_list))
alphagram_solution_dict = defaultdict(list)
for key, value in alphagram_dict.iteritems():
alphagram_solution_dict[value].append(key)
def find_all_anagrams(stringkey):
try:
anagram_list = alphagram_solution_dict[alphagram_dict[stringkey]]
except KeyError:
return None
return anagram_list
with open(wordfile, 'r') as f2:
wordlist = [find_all_anagrams(line.rstrip().upper()) for line in f2]
return find_typos(wordlist)
if __name__ == "__main__":
if len(sys.argv) == 3:
try:
lexicon = sys.argv[1]
wordfile = sys.argv[2]
print(setup(lexicon, wordfile))
except Exception:
print("Something went wrong. Sorry.")
print Exception
else:
print("Wrong number of arguments. Call with lexicon file, then word list file.")
|
fb0eeafe7eb45b469d151b4ed7e97672191d87b6 | buy/leetcode | /python/15.three_sum.py | 1,153 | 3.703125 | 4 | # Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
# Note:
# Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
# The solution set must not contain duplicate triplets.
# For example, given array S = {-1 0 1 2 -1 -4},
# A solution set is:
# (-1, 0, 1)
# (-1, -1, 2)
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
num.sort()
result = []
for i in range(len(num)):
twoSumTuples = self.twoSum(num[i+1:], 0 - num[i])
if twoSumTuples:
for pair in twoSumTuples:
threeSum = [num[i]] + pair
if threeSum not in result:
result.append(threeSum)
return result
def twoSum(self, num, target):
pairMap, result = {}, []
for n in num:
if n in pairMap:
result.append([target - n, n])
else:
pairMap[target - n] = True
return result
|
6cb22747e3870ac4b4ad00bd20e1421a9b4cb35a | bmanandhar/python-practice | /06_morse_encode.py | 1,495 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 09:44:12 2018
@author: bijayamanandhar
"""
# 06 Morse Encode
# Build a function, `morse_encode(str)` that takes in a string (no
# numbers or punctuation) and outputs the morse code for it. See
# http://en.wikipedia.org/wiki/Morse_code. Put two spaces between
# words and one space between letters.
#
# You'll have to type in morse code: I'd use a hash to map letters to
# codes. Don't worry about numbers.
#
# I wrote a helper method `morse_encode_word(word)` that handled a
# single word.
#
# Difficulty: 2/5
CODE = {'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..'}
#
def morse_encode(str):
word_arr = str.split()
morse_arr = [ morse_encode_word(word) for word in word_arr ]
return " ".join(morse_arr).strip()
def morse_encode_word(word):
letters = list(word) # Pythonic way to split word into letters
code = [ CODE[letter.upper()] for letter in letters ]
return " ".join(code)
print("Test for morse encode")
print(morse_encode("cat") == "-.-. .- -")
print(morse_encode("cat in hat") == "-.-. .- - .. -. .... .- -")
print("== == == == == ==") |
0c87119b5214805f2db3cdfc1087bc785cb7bec0 | 3rmack/python_proj | /str.format.py | 1,158 | 3.796875 | 4 | s = "{0} was {age}. {age} is a good age."
y = s.format("nick", age="25")
print(y)
list = ["one", "two", "three"]
pattern = "1 is {0[0]}, 2 is {0[1]}, 3 = {0[2]}"
str = pattern.format(list)
print(str)
import decimal
print("{0} {0!s} {0!r} {0!a}".format(decimal.Decimal("93.4")))
print("{0} {0!s} {0!r} {0!a}".format("dfsdfs"))
movie = "映画のゴジラ"
print("{0!s}".format(movie))
print("{0!r}".format(movie))
print("{0!a}".format(movie))
#print("{0!c}".format(movie))
str2 = "The truth is out there"
print("{0:2^45}".format(str2))
minwidht = 3
maxwidth = 55
print("{0}".format(str2[minwidht:maxwidth]))
print("{0:>{1}.{2}}".format(str2, minwidht, maxwidth))
str3 = 88499392
print("{0:#b} {0:#o} {0:#x} {0:b} {0:o} {0:x}".format(str3))
str4 = -65744.845
print("{0:$>15} {1:*>-20.5e}".format(str3, str4))
str5 = 0xDEFACE
print("{0:#d}".format(str5))
import locale
locale.setlocale(locale.LC_ALL, "")
print("{0:n} $ {1:n}".format(str3, str4))
locale.setlocale(locale.LC_ALL, "C")
print("{0:n} $ {1:n}".format(str3, str4))
#locale.setlocale(locale.LC_ALL, 'en_US')
#print("{0:n} $ {1:n}".format(str3, str4))
import sys
end = sys.maxunicode
print(end) |
fbfca29f454d252100bf18ed9d2f7e48a6620609 | pdvelez/miscellaneous_exercises | /recursion/sum_positive_integers.py | 423 | 4.0625 | 4 | """
This exercise can be found at
http://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-recursion.php
"""
def sum_positive_integers_mult_2(n):
"""
Sum of positive integers of n+(n-2)+(n-4)...(until n-x <= 0)
"""
if n <= 0:
return n
else:
return n + sum_positive_integers_mult_2(n - 2)
if __name__ == '__main__':
print(sum_positive_integers_mult_2(10)) |
1ddfb71d135632b5f732bd61725419a4308769c4 | dararod/python-101 | /cashier/app.py | 1,413 | 3.96875 | 4 | # Aplicacion de Maquina Registradora
# int = Integer (EN) -> Numero Entero (ES)
# str = String (EN) -> Cadena de Caracteres (ES) Textos o Letras
def caja_registradora():
lista_de_productos = obtener_lista_de_productos()
mostrar_resumen(lista_de_productos)
def crear_producto(nombre_del_producto, precio):
prod = {
"nombre": str(nombre_del_producto),
"precio": int(precio)
}
return prod
def obtener_lista_de_productos():
lista_de_productos = []
preguntar_de_vuelta = True
while preguntar_de_vuelta:
# obtiene el nombre del producto del usuario
nombre_del_producto = input("Ingrese producto: ")
precio_del_producto = input("Ingrese precio del producto: ")
# se crea un producto
prod = crear_producto(nombre_del_producto, precio_del_producto)
# agrega el producto a la lista
lista_de_productos.append(prod)
# preguntar si desea continuar
continuar = int(input("Desea agregar otro item?: (0: No/1: Si)"))
if continuar == 1:
continue
else:
preguntar_de_vuelta = False
break
return lista_de_productos
def mostrar_resumen(lista_de_prod):
print("-----------------------------")
total = 0
for prod in lista_de_prod:
print(prod["nombre"] + " Precio: " + str(prod["precio"]))
total = total + prod["precio"]
print("-----------------------------")
print("Total a Pagar: " + str(total))
caja_registradora()
|
2444527d25b4063875ef45f20aaaaaff82299ffe | vipulshah31120/PythonDataStructures | /JugglingAlgo.py | 1,115 | 3.9375 | 4 | #d = by which number we want to rotate
# Function to left rotate arr[] of size n by d
def leftrotate(arr, d, n) :
g_c_d = gcd(d, n) #d = d % n
for i in range (g_c_d) :
temp = arr[i] # move i-th values of blocks
j = i
while 1 :
k = j+d # i, j, k are positions of the elements in Array
if k>= n : # The element have to be rotated
k = k-n
if k == i : # The element is already in rotated position
break
arr[j] = arr[k] # elements get swapped
j = k
arr[j] = temp # after all the iterations in while loop, value of j is retrieved from temp
def printarray(arr, size) :
for i in range (size) :
print(arr[i], end=' ')
def gcd(a, b) : # Function to get gcd of a and b
if b==0 :
return a
else :
return gcd(b,a % b ) #gcd(d,n) blocks are made
arr = [1, 2, 3, 4, 5, 6, 7]
n = len(arr)
d = 2
leftrotate(arr, d, n)
printarray(arr, n)
|
6909396573a8bd7e1df2f306d8d1ea539334fd7b | cq146637/Advanced | /6/6-4.py | 877 | 4.0625 | 4 | """
创建可管理的对象属性
"""
from math import pi
class Circle(object):
"""
使用内置的property函数为类创建可管理属性
fget,fset,fdel对应相应的属性
"""
def __init__(self, radius):
self.radius = radius
def getRadius(self):
# 使用访问器使得取值能够更加灵活,并且能隐藏相关的操作
return self.radius
def setRadius(self, value):
# if not isinstance(value, (int,float,long)): python2
# python 中 int 自动提升到long
if not isinstance(value, (int, float)):
raise ValueError('Wrong Type.')
self.radius = float(value)
def getArea(self):
return self.radius ** 2 * pi
R = property(getRadius, setRadius)
if __name__ == '__main__':
c = Circle(3.2)
print(c.R)
c.R = 2
print(c.R)
|
d4683b1cdfab0273c172533dadf29202a04e263a | SandyHoffmann/ListasPythonAlgoritmos | /Lista 1/SH-PCRG-AER-Alg-01-Ex-13.py | 249 | 3.90625 | 4 | #Pegando base e altura
b = float(input("Me de a base do triangulo: "))
h = float(input("Me de a altura do triangulo: "))
#Fazendo o calculo de área de triangulo
calculo = (b*h)/2
#Exibindo resultado
print(f'A área do triangulo é de {calculo}')
|
6ae4cad02e48d8a353a104753c2cc5f539536aa0 | DavidMutchler/RoseboticsCS1Tools | /Grader/csse120-grading/201430/Session16_Test2_201430/solution/src/m2.py | 4,632 | 3.84375 | 4 | """
Test 2, problem 2.
Authors: David Mutchler, Chandan Rupakheti, their colleagues,
and SOLUTION by David Mutchler. April 2014.
""" # DONE: PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST functions in this module. """
test_problem2a()
test_problem2b()
def test_problem2a():
""" Tests the problem2a function. """
# DONE: Implement this function, using it to test the NEXT
# function. Write the two functions in whichever order you prefer.
# Include at least 2 tests, i.e., 2 calls to the function to test.)
print()
print('--------------------------------------------------')
print('Testing the problem2a function:')
print('NOTE: You should include at least TWO tests.')
print('--------------------------------------------------')
seq1 = [4, 66, 9, -2, 55, 0]
seq2 = [7, 22, 5, 10, -5, 9]
correct_answer = [11, 88, 14, 8, 50, 9]
print()
print('Test 1, using {} and {}:'.format(seq1, seq2))
print('Correct answer is: {}'.format(correct_answer))
print('Answer returned is: {}'.format(problem2a(seq1, seq2)))
seq1 = [100, 200, 300, 5, 4, 3, 2, 1, 0, -100, 199]
seq2 = [500, 100, 666, 0, 0, 1, 7, 7, 0, 1100, -98]
correct_answer = [600, 300, 966, 5, 4, 4, 9, 8, 0, 1000, 101]
print()
print('Test 2, using {} and {}:'.format(seq1, seq2))
print('Correct answer is: {}'.format(correct_answer))
print('Answer returned is: {}'.format(problem2a(seq1, seq2)))
def problem2a(list1, list2):
"""
Returns a new list that is the item-by-item sum
of the two given lists.
For example, if the given lists are:
[4, 66, 9, -2, 55, 0]
[7, 22, 5, 10, -5, 9]
then the returned list should be:
[11, 88, 14, 8, 50, 9]
Another example: if the given lists are:
[100, 200, 300, 5, 4, 3, 2, 1, 0, -100, 199]
[500, 100, 666, 0, 0, 1, 7, 7, 0, 1100, -98]
then the returned list should be:
[600, 300, 966, 5, 4, 4, 9, 8, 0, 1000, 101]
Preconditions: the given lists are lists of numbers
and their lengths are the same.
"""
# DONE: Implement and test this function.
new_list = []
for k in range(len(list1)):
new_list.append(list1[k] + list2[k])
return new_list
def test_problem2b():
""" Tests the problem2b function. """
# DONE: Implement this function, using it to test the NEXT
# function. Write the two functions in whichever order you prefer.
# Include at least 2 tests, i.e., 2 calls to the function to test.)
print()
print('--------------------------------------------------')
print('Testing the problem2b function:')
print('NOTE: You should include at least TWO tests.')
print('--------------------------------------------------')
seq1 = [4, 66, 9, -2, 55, 0]
seq2 = [7, 22, 5, 10, -5, 9]
correct_answer = [11, 88, 14, 8, 50, 9]
print()
print('Test 1, using {} and {}:'.format(seq1, seq2))
print('Correct answer is: {}'.format(correct_answer))
problem2b(seq1, seq2)
print('Mutated list1 is: {}'.format(seq1))
print('Unmutated list2 remains: {}'.format(seq2))
seq1 = [100, 200, 300, 5, 4, 3, 2, 1, 0, -100, 199]
seq2 = [500, 100, 666, 0, 0, 1, 7, 7, 0, 1100, -98]
correct_answer = [600, 300, 966, 5, 4, 4, 9, 8, 0, 1000, 101]
print()
print('Test 2, using {} and {}:'.format(seq1, seq2))
print('Correct answer is: {}'.format(correct_answer))
problem2b(seq1, seq2)
print('Mutated list1 is: {}'.format(seq1))
print('Unmutated list2 remains: {}'.format(seq2))
def problem2b(list1, list2):
"""
MUTATES the first of the two given lists so that it becomes
the item-by-item sum of the two given lists.
For example, if the given lists are:
[4, 66, 9, -2, 55, 0]
[7, 22, 5, 10, -5, 9]
then the first of those two lists should mutate into:
[11, 88, 14, 8, 50, 9]
Does NOT return anything explicitly (so None is returned implicitly).
Preconditions: the given lists are lists of numbers
and their lengths are the same.
"""
# DONE: Implement and test this function.
for k in range(len(list1)):
list1[k] = list1[k] + list2[k]
#------------------------------------------------------------------------
# If this module is running at the top level (as opposed to being
# imported by another module), then call the 'main' function.
#------------------------------------------------------------------------
if __name__ == '__main__':
main()
|
399757235de5ba4badd976d78699a0f622430a8e | manuel-martinez-dev/rps_1 | /rps beta 1.py | 3,953 | 4.125 | 4 | #!/usr/bin/env python3
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
import random
import sys
from colorama import init
from colorama import Fore, Back, Style
print(Fore.RED, Style.DIM + "Are you ready to play ROCK, PAPER, SCISSORS?"'\n')
print(Style.RESET_ALL)
moves = ['rock', 'paper', 'scissors']
"""The Player class is the parent class for all of the Players
in this game"""
class Player:
def move(self):
return 'rock'
def learn(self, my_move, their_move):
pass
class RandomPlayer(Player):
def move(self):
return random.choice(moves)
class HumanPlayer(Player):
def move(self):
while True:
chose = input("whatcha u gonna play?:"'\n')
if chose in moves:
return chose
class ReflectPlayer(Player):
def __init__(self):
self.chose = random.choice(moves)
def move(self):
return self.chose
def learn(self, my_move, their_move):
self.chose = their_move
class CyclePlayer(Player):32
def __init__(self):
self.choices = 0
def move(self):
return moves[self.choices]
def learn(self, my_move, their_move):
if self.choices == 2:
self.choices = 0
else:
self.choices += 1
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
self.score1 = 0
self.score2 = 0
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
if beats(move1, move2):
self.score1 += 1
print(Fore.BLUE + "YOU Have won!")
elif beats(move2, move1):
self.score2 += 1
print(Fore.RED + "JOHNNY5 Has won!")
else:
print(Fore.YELLOW + "DRAW!!")
# print(f"Player 1: {self.score1} Player 2: {self.score2}")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
def more_rounds(self):
for round in range(5):
print(f"Round {round+1}:")
self.play_round()
print(Fore.WHITE + f"YOU: {self.score1} JOHNNY5: {self.score2}")
def play_game(self):
print("Game start!"'\n')
for round in range(1):
print(f"Round {round}:")
self.play_round()
print(Fore.WHITE + f"YOU: {self.score1} JOHNNY5: {self.score2}")
if self.score1 > self.score2:
print(Fore.GREEN + "YOU ARE TRIUMPHANT!")
elif self.score1 < self.score2:
print(Fore.BLUE + "JOHNNY5 is VICTORIOUS!")
else:
print(Fore.YELLOW + "Outta breath?-DRAW!!")
print('\n'"Game over!")
mode = input("play longer?[yes,no]"'\n')
while True:
if mode == 'no':
print("Until next time...")
sys.exit(0)
elif mode == 'yes':
self.more_rounds()
if self.score1 > self.score2:
print(Fore.GREEN + "YOU ARE TRIUMPHANT!")
elif self.score1 < self.score2:
print(Fore.BLUE + "JOHNNY5 is VICTORIOUS!")
else:
print(Fore.YELLOW + "Outta breath?-DRAW!!")
print('\n'"Game over!")
sys.exit(0)
else:
print("YOU should have chosen wisely - GOODBYE!!!")
sys.exit(0)
if __name__ == '__main__':
behaviors = [Player(), RandomPlayer(), CyclePlayer()]
behavior = random.choice(behaviors)
human = HumanPlayer()
game = Game(human, behavior)
game.play_game()
# game.play_game()
# print(help())
|
619de3e1284ac42a2e492a9b79895b6d75dd5b37 | git874997967/LeetCode_Python | /mid/leetCode3.py | 787 | 3.71875 | 4 | #3. Longest Substring Without Repeating Characters
def lengthOfLongestSubstring2(s):
# use the queue to save length only but not the actual string
dq, result = [],0
for char in s:
while char in dq:
dq.pop(0)
dq.append(char)
result = max(result, len(dq))
return result
def lengthOfLongestSubstring(s):
result = start = 0
charMap = {}
for i, v in enumerate(s):
if v in charMap:
# update the new start
start = max(start, charMap[v] + 1)
result = max(result, i - start + 1)
charMap[v] = i
print(result)
return result
lengthOfLongestSubstring("abcabcbb")
lengthOfLongestSubstring("bbbbb")
lengthOfLongestSubstring("pwwkew")
lengthOfLongestSubstring("") |
434f97d4ac50db41bcd1b7b4a56760417119a835 | alaguraja006/pythonExcercise | /listEx.py | 305 | 3.71875 | 4 | ls = [10,20,'hai',-10,23.03]
print(ls)
print(ls[3])
print(ls[3:5])
print(ls*3)
print(len(ls))
print(ls[::-1])
ls.append(40)
print(ls)
ls.remove('hai')
print(ls)
del(ls[1])
print(ls)
ls.insert(1,1000)
ls.sort()
print(ls)
ls.sort(reverse=True)
print(ls)
print(max(ls))
print(min(ls))
ls.clear()
print(ls) |
de3af90f7ce91bca90328ad11e1bc1103e38f483 | d4rkr00t/leet-code | /python/leet/950-reveal-cards-in-increasing-order.py | 584 | 3.546875 | 4 | # Reveal Cards In Increasing Order
# https://leetcode.com/problems/reveal-cards-in-increasing-order/
# medium
import collections
def deckRevealedIncreasing(deck: [int]) -> [int]:
N = len(deck)
index = collections.deque(range(N))
ans = [None] * N
for card in sorted(deck):
ans[index.popleft()] = card
print()
if index:
index.append(index.popleft())
return ans
print(deckRevealedIncreasing([17,13,11,2,3,5,7]), [2,13,3,11,5,17,7])
# [17,13,11,2,3,5,7]
#
# 0 1 2 3 4 5 6
# 2 3 4 5 6 1
# 4 5 6 1 3
# 6 1 3 5
# 3 5 1
# 1 5
# 5
|
95336dd2dae8606c598432134d0df67bf7eb88aa | joyce04/coding_practice | /algorithm_practice/recursion/reverse_string.py | 393 | 3.6875 | 4 | # reverse a string
def reverse_loop(sent):
n_str = []
for i in range(len(sent)-1, -1, -1):
n_str.append(sent[i])
return ''.join(n_str)
def reverse_recursive(sent):
size = len(sent)
if len(sent) == 1:
return sent
last_char = sent[size-1]
return last_char + reverse_recursive(sent[0:size-1])
print(reverse_loop('yoyo mastery'))
print(reverse_recursive('yoyo mastery')) |
4d2e78a90cc9bb35658e3cc7d090d6363f029963 | Juan128524/proyecto1 | /main.py | 133 | 3.53125 | 4 | print("HOLA")
print("bienvenido al mundo de python")
print("Nombre: Juan Avila")
print("Paralelo: Septimo C")
i=8
c=10
a=i*c
print(a)
|
2787e04b5298440019ebcaae48e8bad4d2b2385f | claudioPOO/ejericio2-unidad3 | /claseManejadorHelado.py | 1,870 | 3.6875 | 4 | from claseHelado import Helado
from claseSabor import Sabor
class ManejaHelado:
__pedido=[]
def __init__(self):
self.__pedido=[]
def cargarPedido(self,sabores):
i=len(self.__pedido)
print('Carga de pedidos(finalice con 0)-------')
pedido=int(input('Numero de pedido: '))
while(pedido!=0):
gramos=int(input('Gramos del helado: '))
unHelado=Helado(gramos)
self.__pedido.append(unHelado)
sabor=str(input('Sabores: (termine con nada) '))
while(sabor!='nada'):
sa=sabores.buscaSabor(sabor)
if(sa!=0):
self.__pedido[i].agregarSabor(sa)
else:
print('Sabor no encontrado')
sabor=str(input('Sabores: (termine con nada) '))
i=i+1
pedido=int(input('Numero de pedido: '))
def mostrarPedidos(self):
for i in range(len(self.__pedido)):
print(self.__pedido[i].getGramos())
def buscaporNumero(self,numero):
i=0
gramosVendidos=0
while(i<len(self.__pedido)):
total=0
if(int(self.__pedido[i].Buscaxnumero(numero)==1)):
cant=self.__pedido[i].cGramos()
sab=self.__pedido[i].cSabores()
total=cant/sab
gramosVendidos=gramosVendidos+total
i=i+1
return gramosVendidos
def BuscaGR(self,gr):
i=0
while(i<len(self.__pedido)):
if(self.__pedido[i].cGramos()==int(gr)):
self.__pedido[i].getGramos()
i=i+1
def __del__(self,pedido):
print('Borrando pedido nro {}...'.format(pedido+1))
del self.__pedido[pedido]
print('Pedido Borrado') |
4bfd96041b6901b1d920f86b358063e9d2a806bd | rsiew11/TicTacToe | /main.py | 8,336 | 3.765625 | 4 | from Tkinter import Tk, Button, Label
from tkFont import Font
from Board import Board
import socket
class GUI:
def __init__(self):
self.app = Tk()
self.app.title('TicTacToe')
self.app.resizable(width=False, height=False)
self.font = Font(family="Helvetica", size=100)
self.board = Board("ai")
self.buttons = {}
self.backBtn = None
self.gameOverLabel = None
#menu buttons
self.mode=""
self.aiBtn=None
self.hostBtn=None
self.joinBtn=None
#networking constructs
self.conn = None
self.addr = None
self.TCP_IP = '127.0.0.1'
self.TCP_PORT = 5007
self.BUFFER_SIZE = 128
self.s = None
# begin the menu
self.menuScreen()
def menuScreen(self):
w = 50
p = 50
self.mode = 'menu'
#buttons here_----------------------------------------------------------
self.aiBtn = Button(self.app, width=w, pady=p,
text='Play Against AI!', command=self.playAI)
self.hostBtn = Button(self.app, width=w, pady=p,
text='Host a game!', command=self.hostGame)
self.joinBtn = Button(self.app, width=w, pady=p,
text='Join a game!', command=self.joinGame)
self.aiBtn.grid(row=0, column=0, sticky="WE")
self.hostBtn.grid(row=1, column=0, sticky="WE")
self.joinBtn.grid(row=2, column=0, sticky="WE")
def playAI(self):
self.mode="ai"
self.destroyMenu()
self.createGrid()
def hostGame(self):
self.app.title('HOST')
self.mode="host"
self.destroyMenu()
waiting = Label(self.app, text = "waiting for player 2!")
waiting.grid(row=0,column=0,sticky="WE",pady=150,padx=150)
### connection!!
self.sh = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sh.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
self.sh.bind((self.TCP_IP, self.TCP_PORT))
self.sh.listen(1)
self.conn, self.addr = self.sh.accept()
data = self.conn.recv(self.BUFFER_SIZE)
print(data)
self.conn.send("ur gonna join")
#setting up the menu stuff
waiting.destroy()
self.createGrid()
# CLosing connection for now
#self.conn.close()
def joinGame(self):
self.app.title('JOIN')
self.mode="join"
self.destroyMenu()
waiting = Label(self.app, text = "waiting for player 1!")
waiting.grid(row=0,column=0,sticky="WE",pady=150,padx=150)
### connection!!
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
self.s.connect((self.TCP_IP,self.TCP_PORT))
self.s.send("ur the host!!")
data = self.s.recv(self.BUFFER_SIZE)
print(data)
#setting up the menu stuff
waiting.destroy()
self.createGrid()
#make the player wait!!
self.waitForMove()
def destroyMenu(self):
self.aiBtn.destroy()
self.hostBtn.destroy()
self.joinBtn.destroy()
def createGrid(self):
if (self.mode == 'ai'):
self.board = Board('ai')
elif (self.mode == 'host'):
self.board = Board('host')
elif(self.mode == 'join'):
self.board = Board('join')
for col,row in self.board.fields:
handler = lambda x=col,y=row: self.move(x,y)
button = Button(self.app, command=handler, font=self.font,
disabledforeground='black', state='normal',
width=4, height=2, pady=0)
button.grid(row=row, column=col)
self.buttons[col,row] = button
self.backBtn = Button(self.app, text='Back to Menu',
command=self.backButton)
self.backBtn.grid(row=self.board.size, column=1,
columnspan=self.board.size/2, sticky="WE")
self.update()
def backButton(self):
#destroy the current windows based on what mode we are on rn
# ie human vs AI mode
for col,row in self.board.fields:
self.buttons[col,row].destroy()
if (self.mode == 'host'):
self.conn.close()
elif (self.mode == 'join'):
self.s.close()
if (self.gameOverLabel != None):
self.gameOverLabel.destroy()
self.backBtn.destroy()
self.menuScreen()
def waitForMove(self):
self.disableButtons()
winning = self.board.won()
if (winning != None):
self.gameOver(winning)
return
if (self.mode == 'host'):
## make a label to show that it's other turn
while(1):
#wait for player 2's move
print("waiting for joiner")
data = self.conn.recv(self.BUFFER_SIZE)
print(data)
if (len(data)==3):
x = int(data[0])
y = int(data[2])
break
elif (self.mode == 'join'):
## make a label to show that it's other turn
while (1):
#wait for player 1's move
print("waiting for host")
data = self.s.recv(self.BUFFER_SIZE)
print(data)
if (len(data)==3):
x = int(data[0])
y = int(data[2])
break
self.board = self.board.move(x,y)
self.update()
def move(self,x,y): # the x and y are coords of button pushed
if (self.mode == 'ai'): # player vs AI
self.app.config(cursor="watch")
self.app.update()
self.board = self.board.move(x,y)
self.update()
# find the AI move via minimax
move = self.board.bestMove()
print(move)
if (move):
self.board = self.board.move(*move)
self.update()
self.app.config(cursor="")
elif (self.mode == 'host'): # player 1
self.app.config(cursor="watch")
self.app.update()
self.board = self.board.move(x,y)
self.update()
#send move to player 2
self.conn.send(str(x)+','+str(y))
self.waitForMove()
#self.conn.close()
elif (self.mode == 'join'): # player 2
# wait for player 1 move
self.app.config(cursor="watch")
self.app.update()
self.board = self.board.move(x,y)
self.update()
self.s.send(str(x)+','+str(y))
self.waitForMove()
#self.s.close()
def gameOver(self,winning):
try:
for x,y in self.buttons:
self.buttons[x,y]['state'] = 'disabled'
for x,y in winning:
self.buttons[x,y]['disabledforeground'] = 'red'
for col,row in self.board.fields:
self.buttons[col,row].destroy()
self.gameOverLabel = Label(self.app, text = "GAME OVER!")
self.gameOverLabel.grid(row=0,column=0,sticky="WE",pady=250,padx=250)
except:
self.gameOverLabel = Label(self.app, text = "GAME OVER!")
self.gameOverLabel.grid(row=0,column=0,sticky="WE",pady=250,padx=250)
return
def update(self):
for (x,y) in self.board.fields:
gridVal = self.board.fields[x,y]
self.buttons[x,y]['text'] = gridVal
if (gridVal != self.board.empty):
self.buttons[x,y]['state'] = 'disabled'
else:
self.buttons[x,y]['state'] = 'normal'
for (x,y) in self.board.fields:
self.buttons[x,y].update()
winning = self.board.won() # the winning coords
if (winning != None):
self.gameOver(winning)
def disableButtons(self):
try:
for x,y in self.buttons:
self.buttons[x,y]['state'] = 'disabled'
except:
return
def mainloop(self):
self.app.mainloop()
if __name__ == '__main__':
GUI().mainloop()
|
d7d25a847ca805c5161e5c043fcff2704ff1719b | avonhatten/trumpSlackBot | /slackbot/trump.py | 458 | 3.515625 | 4 | #!/usr/bin python
import os
from donaldbot import DonaldBot
theDonald = DonaldBot()
# Get the current directory's path
dirname = os.path.dirname(os.path.abspath(__file__))
# Construct the path to the book
book = os.path.join(dirname, 'trumpData.txt')
# Have the bot read the book
theDonald.read(book)
response = raw_input("Ask Trump: ")
if "you" in response:
response == "I"
response = theDonald.generate_text(16, response)
print(" ")
print(response)
|
d6228eac499e8a4e3b8dad41873d3606395f1667 | dhermes/project-euler | /python/complete/no042.py | 1,254 | 3.953125 | 4 | #!/usr/bin/env python
# By converting each letter in a word to a number corresponding to
# its alphabetical position and adding these values we form a word
# value. For example, the word value for SKY is
# 19 + 11 + 25 = 55 = t_(10). If the word value is a triangle number
# then we shall call the word a triangle word.
# Using words.txt (right click and 'Save Link/Target As...'), a 16K
# text file containing nearly two-thousand common English words,
# how many are triangle words?
# I've renamed words.txt as no042.txt
import string
from python.decorators import euler_timer
from python.functions import get_data
from python.functions import reverse_polygonal_number
def word_to_value(word):
letters = string.uppercase
return sum(letters.find(letter) + 1 for letter in word)
def num_triangle():
# Assumes file is "A","ABILITIY","ABLE",...
words = get_data(42).strip('"').split('","')
vals = [word_to_value(word) for word in words]
triangle_hash = {}
count = 0
for val in vals:
if reverse_polygonal_number(3, val, triangle_hash) != -1:
count += 1
return count
def main(verbose=False):
return num_triangle()
if __name__ == '__main__':
print euler_timer(42)(main)(verbose=True)
|
9fbb155a090664cced56bf6deeb5f229a70aca70 | bthowe/data_science | /estimation/statistics/statistical_tests/a_b_testing/bayesian_a_b.py | 1,072 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def calc_distributions(successes_A, failures_A, successes_B, failures_B, num_samples=1000):
"""Draws num_samples from beta distributions where alpha and beta are determined by the number of successes and
failures. This only holds for binary outcome since beta distribution is a conjugate distribution of the
binomial distribution"""
A_dist = np.random.beta(1 + successes_A, 1 + failures_A, shape=num_samples)
B_dist = np.random.beta(1 + successes_B, 1 + failures_B, shape=num_samples)
return A_dist, B_dist
def prob_A_wins(A_dist, B_dist, wiggle=0):
"""Calculates the probability a random draw from distribution A is greater than a random draw from B plus a wiggle
constant."""
return np.sum(A_dist > (B_dist + wiggle)) / float(num_samples)
def plot_A_B(A_dist, B_dist):
"""Plots the distribution A and B."""
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(1,1,1)
ax.hist(A_dist, color='r', alpha=0.3)
ax.hist(B_dist, color='b', alpha=0.3)
plt.show()
|
17f8b6715d8006f8d04176b7bfc80eb62b7cf693 | rydevera3/A-Primer-on-Scientific-Programming-with-Python-Solutions | /Chapter 1/1plus1.py | 372 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 31 21:32:07 2014
@author: rdevera
"""
# Chapter 1: Exercise 1
# The first exercise concerns some very basic mathematics. Write a Python program
# that stores of the result of the computation 1+1 in a variable and then prints the
# value of the variable.
# assign a variable to 1+1
a = 1+1
# print the value of a
print a |
66b96196ed88e96bca4c8d9b3f130ca058e6c368 | meghnavarma0/DSA-Python | /DP/ugly.py | 409 | 3.640625 | 4 | def maxDiv(a, b):
while a % b == 0:
a /= b
return a
def isUgly(no):
no = maxDiv(no, 2)
no = maxDiv(no, 3)
no = maxDiv(no, 5)
return 1 if no == 1 else 0
def nthUgly(n):
i = 1
count = 1
while count < n:
i += 1
if isUgly(i):
count += 1
return i
t = int(input())
while t:
n = int(input())
print(nthUgly(n))
t -= 1
|
6b011144b50b1584ba3bf72b0087022165202155 | tangly1024/learning_python | /Chapter-4-Functional-Programming/higher_function_return_function.py | 1,956 | 3.734375 | 4 | # coding=utf-8
"""
函数作为返回值
“闭包(Closure)” 相关参数和变量都保存在返回的函数
"""
"""
举例,可变参求和函数
"""
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
# 但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数:
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 2, 3)
f()
"""
闭包引用循环变量
返回函数不要引用任何循环变量,或者后续会发生变化的变量。
如果一定要引用循环变量?方法是再创建一个函数,用该函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变:
"""
def count():
def f(j):
def g():
return j * j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
# 闭包练习
# 创建一个独立组建
def createCounter():
def counter(x):
while True:
yield x
x += 1
x = 1
g = counter(x)
def get():
return next(g)
return get
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!')
"""
lambda
"""
"""
以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
"""
list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
f = lambda x: x * x
print(f(2))
# 也可以返回函数
def build(x, y):
return lambda: x * x + y * y
ff = build(1, 2)
print(ff())
|
98b85680f2a2981ea1b34be126fbc1fff7784762 | aravindsbr/json_parser | /test_json_parser.py | 786 | 3.515625 | 4 | import unittest
import json
from json_parser import json_data, extracting_values_from_json
from unittest.mock import patch
class JSONParserTest(unittest.TestCase):
def test_extracting_values_from_json(self):
"""
Unit test case to test the json_extract function
"""
# expected
expected = ['System', 'videoMode', 'windowMode', 'verticalSync',
'textureMode', 'anisotropy', 'multisample', 'supersample',
'rate', 'apply']
# actual
print("TESTING")
actual = extracting_values_from_json(json_data, "identifier")
# test
self.assertIsNotNone(actual)
self.assertEqual(actual, expected)
self.assertListEqual(actual, expected)
if __name__ == '__main__':
unittest.main()
|
4e1e184f9ad078411889a6b4f1102790fc0d3e7b | bak-minsu/geditdone | /geditdone/generichelpers.py | 339 | 3.75 | 4 | class Stack:
items = []
def __init__(self, items = []):
if items != None and len(items) > 0:
self.items = items
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1] if len(self.items) > 0 else None |
0cdff944d2ec29ef309a3a990b93a1454aef8237 | mrdhindsa/Artificial-Intelligence | /tictactoe/tictactoe.py | 4,495 | 3.984375 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
if(board == initial_state()): # Game is in the initial state
return X
if(terminal(board)): # Game is over
return None
# Count the number of "X" and the number of "O": if count_X > count_O return "O" else return "X"
count_X, count_O = 0, 0
for row in board:
for val in row:
if(val == "X"):
count_X += 1
elif(val == "O"):
count_O += 1
if(count_X > count_O):
return O
return X
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
if(terminal(board)): # Game is over
return None
# Find all coordinates on the board that are None, and return a set of those coordinates
actions = set()
for i in range(len(board)):
for j in range(len(board[0])):
if(board[i][j] == None):
actions.add((i,j))
return actions
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
p = player(board) # Either "X" or "O"
if(board[action[0]][action[1]] != None):
raise Exception
newboard = copy.deepcopy(board)
newboard[action[0]][action[1]] = p
return newboard
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
# 3 rows, 3 cols, 2 diagonals
coord_matrix = [[(0,0), (0,1), (0,2)], # row0
[(1,0), (1,1), (1,2)], # row1
[(2,0), (2,1), (2,2)], # row2
[(0,0), (1,0), (2,0)], # col0
[(0,1), (1,1), (2,1)], # col1
[(0,2), (1,2), (2,2)], # col2
[(0,0), (1,1), (2,2)], # diag0
[(0,2), (1,1), (2,0)]] # diag1
for coord0, coord1, coord2 in coord_matrix:
if(board[coord0[0]][coord0[1]] == board[coord1[0]][coord1[1]] == board[coord2[0]][coord2[1]] and board[coord0[0]][coord0[1]] != None):
return board[coord0[0]][coord0[1]]
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
flag_None = 0
for row in board:
for val in row:
if(val == None):
flag_None = 1 # If flag = 1 -> result is pending, not draw
w = winner(board)
if(w != None or (w == None and flag_None == 0)): # someone already won or it is a Draw (no more moves to make)
return True
return False
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
w = winner(board)
if(w == X):
return 1
elif(w == O):
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if(terminal(board)): # Game is over
return None
p = player(board) # X is max player, O is min player
action_to_return = None
if (p == X):
value = -math.inf
for action in actions(board):
val = min_value(result(board, action))
if(val > value):
value = val
action_to_return = action
else:
value = math.inf
for action in actions(board):
val = max_value(result(board, action))
if(val < value):
value = val
action_to_return = action
return action_to_return
def min(x, y):
'''
Returns the minimum value.
'''
return x if x < y else y
def max(x, y):
'''
Returns the maximum value.
'''
return x if x > y else y
def max_value(board):
'''
Helper Function for minimax().
'''
if(terminal(board)):
return utility(board)
value = -math.inf
for action in actions(board):
value = max(value, min_value(result(board, action)))
return value
def min_value(board):
'''
Helper Function for minimax().
'''
if(terminal(board)):
return utility(board)
value = math.inf
for action in actions(board):
value = min(value, max_value(result(board, action)))
return value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.