blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
5b427d2d4d67cda7cebba942e5944d0732f2b63f | amarinas/algo | /chapter_1_fundamentals/birthday.py | 272 | 4.15625 | 4 | def birthday(month, day):
# you say its your birthday
# if 2 given numbers represent your month and day print statements
if month == 3 and day == 18:
print "how did you know?"
else:
print "just another day"
birthday(3,18)
birthday(5,12)
|
911dad7c520a360c82eb1b32530d2c25d7b47fbf | EduardoFilip/Estudo-Python | /meu_app.py | 799 | 4.03125 | 4 | a = int(input("Digite um número: "))
b = int(input("Digite outro número: "))
mult = a * b
div = a / b
som = a + b
sub = a - b
operacao = input("Qual operação você deseja realizar? \n Escolha uma das opções abaixo: \n M - Multiplicação \n D - Divisão \n S - Soma \n U - Subtracao \n ")
if operacao == 'M' or operacao == 'm':
print("O resultado da operação é: {} " .format(mult))
elif operacao == 'D' or operacao == 'd':
print("O resultado da operação é: {} " .format(div))
elif operacao == 'S' or operacao == 's':
print("O resultado da operação é: {} " .format(som))
elif operacao == 'U' or operacao == 'u':
print("O resultado da operação é: {} " .format(sub))
else:
print("Operação escolhida inválida!")
input("Pressione enter para fechar a janela...") |
a193b3031f0b7284ad4bcbff1e2babb1d63dc37f | bluehood/benford_analysis | /bin/misc/inflation_adjustment.py | 1,499 | 3.578125 | 4 | #!/usr/bin/python3
import sys
def usage():
print(f'Adjust for inflation in financial data. The rate of inflation will need to be specified as a parameter to the program.')
print(f'{sys.argv[0]} <datafile> <rate of inflation (percentage)> <savefile>')
return(0)
def import_data(input_filename):
# Input data from argv[1] into input_data (newline delimited)
try:
open_file = open(input_filename, "r")
raw_data = open_file.readlines()
input_data = []
for x in raw_data:
input_data.append(x.replace('\n', ''))
open_file.close()
except:
print("[Fatal Error] Failed to read data from report file. Exiting.")
# usage()
exit()
input_data_float = [float(x) for x in input_data]
print(type(input_data_float[0]))
return(input_data_float)
def export_results(export_filename, export_data):
# Write to file
with open(export_filename, 'w') as f:
for item in export_data:
f.write("%s\n" % item)
return(0)
if __name__ == '__main__':
# import dataset
raw_data = import_data(sys.argv[1])
processed_data = []
# increase by inflation amount given in sys.argv[2] as a percentage
inflation_amount = float(sys.argv[2])
for x in raw_data:
processed_data.append(str(round(x * (1 + (inflation_amount / 100)), 3)))
# write out to file
export_results(sys.argv[3], processed_data)
print(processed_data)
|
855f87c0bd9e136e997aa04cfd0609fd371f3b4e | HadzhieV777/SoftUni_Fundamentals_2021 | /Exercise_Text_Processing/05-Emoticon_Finder.py | 194 | 3.578125 | 4 | # 05. Emoticon Finder
text = input()
emojis = [f"{text[index]}{text[index + 1]}"
for index in range(0, len(text))
if text[index] == ":"
]
print("\n".join(emojis)) |
aeae165962a79b23f99bf2ef24956cc04a6572be | JaiRaga/Python-DS-Algorithms | /APA's/strStr.py | 299 | 3.734375 | 4 | def strStr(haystack, needle):
needleLen = len(needle)
for i in range(len(haystack)-1):
if haystack[i:i+needleLen] == needle:
return i
return -1
if __name__ == "__main__":
haystack = input().strip()
needle = input().strip()
print(strStr(haystack, needle)) |
515933bada4455872da1e2e6682b9c85c42cdcb1 | seekerFactory/eatScrambles | /RankingRecommendations/tests.py | 1,803 | 3.59375 | 4 | #! /usr/bin/env python3
import argparse, random
from data import *
from recomends import RModel as RM
def testTopNMatches(critics, rmnd, name, category, matches=3):
print("\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("Top %d matches for critic %s in " %(matches, name) + '% '+ "for category %s\n" %(category))
topm = rmnd.topMatches(critics, name, matches)
for (prctg, name) in topm:
print('%s : %f' % (name, prctg*100) + ' %')
print("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n")
def tested(rmnd, critics, testcase, critic_name, verbose=False):
testTopNMatches(critics, rmnd, critic_name, testcase, 3)
def main():
print("running test")
if args.testcase:
testcase=args.testcase
if testcase == 'movie':
critics=movie_critics
if testcase == 'food':
critics=food_critics
rmnd=RM()
if(args.critic):
critic_name=args.critic
else:
# Choose critic at random
ci=[]
ci=rmnd.getCritics(critics)
critic_name=ci[random.randrange(len(ci)-1)]
tested(rmnd, critics, testcase, critic_name)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Recomendations and Ranking Tests', add_help=True)
parser.add_argument('-v', '--verbose',dest='verbose', action='store_true', help='verbose mode processing shown')
parser.add_argument('-t', '--test',dest='testcase', action='store', choices={'movie', 'food'}, default='movie',help='testcase name')
parser.add_argument('-c', '--critic',dest='critic', action='store', help='critic name')
parser.add_argument('-q', '--quit', dest='quit', action='store_true', help='quit now')
args=parser.parse_args()
if args.verbose:
print(args.verbose)
else: print(args.testcase)
main()
|
58b30467daa79fa10e15831219b6034fe73cdfe1 | Aasthaj01/DSA-questions | /Tree/tree_height.py | 688 | 4.125 | 4 | # Find the height of the given tree using recursion
class Node(object):
def __init__(self, value):
self.value = value
self.right = None
self.left = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def height(self, node):
if node is None:
return 0
else:
ltree = self.height(node.left)
rtree = self.height(node.right)
return 1+max(ltree, rtree)
b = BinaryTree(1)
b.root.left = Node(2)
b.root.right = Node(3)
b.root.left.left = Node(10)
b.root.left.right = Node(20)
b.root.right.left = Node(30)
print(b.height(b.root))
|
5394d2d8237802a930e1c43b1fffc5fb1f2a1090 | non26/testing_buitIn_module | /superMethod/test1_superMethod.py | 603 | 4.53125 | 5 | """
this super method example here takes the argument of two,
first is the subClass and the second is the instance of that subClass
so that the the subClass' instance can use the superClass' attributes
STRUCTURE:
super(subclass, instance)
"""
class Rectangle(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
class Square(Rectangle):
def __init__(self, length):
# super() executes fine now
super(Square, self).__init__(length, length)
s = Square(5)
print(s.area) # 25 |
da93b48d49b0479ecae8c7a55988ddf01ef6f0ce | yongyaoli/pystudy | /sample/c18.py | 2,096 | 3.6875 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
'''
获取对象信息
'''
import types
def fn():
pass
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Hasky(Dog):
def run(self):
print('Hasky is running...')
# type() 函数 判断对象的类型
print(type(123))
print(type('abc'))
print(type(None))
print(type(abs))
a = Animal()
print(type(a))
print(type(123)==type(456))
print(type(123)==int)
# 判断对象是否是函数
print(type(fn)==types.FunctionType)
print(type(abs)==types.BuiltinFunctionType)
print(type(lambda x:x)==types.LambdaType)
print(type(x for x in range(10))==types.GeneratorType)
# 判断class的类型
a = Animal()
d = Dog()
h = Hasky()
print(isinstance(a, Hasky))
print(isinstance(a, Animal))
print(isinstance(d, Hasky))
# 能用 type()判断的基本类型 也可以用 isintance() 判断
print(isinstance('a', str))
print(isinstance(123, int))
print(isinstance(b'a', bytes))
# 判断一个变量是否是某些类型中的一种
print(isinstance([1, 2, 3], (list, tuple)))
print(isinstance((1, 3, 3), (list, tuple)))
print("==="*20)
# dir()函数可以获取对象的所有属性和方法
print(dir('abc'))
print(len('ABC'))
print('ABC'.__len__())
print('ABC'.lower())
print('ABC'.isupper())
# getattr() 可以获取一个对象的属性
# setattr() 可以设置一个对象的属性
# hasattr() 可以判断对象是否包含特定属性
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
print(hasattr(obj, 'x')) # 判断是否有x 属性
print(setattr(obj, 'y', 19)) # 设置一个 属性y ,y的值是 19
print(getattr(obj, 'y')) # 获取一个属性 y的值
print(getattr(obj, 'z', 20)) # 获取一个属性的值,并设置没有值时返回的默认值
# print(getattr(obj, 'zz'))
print(getattr(obj, 'power')) # 获取属性 power
f = getattr(obj, 'power') # 获取属性 power 并赋值到 f
print(f)
print(f())
|
867ec93cf4bdb880abd92e5431680a6cd68c2f85 | zekesimonsson/easy-trilateration | /easy_trilateration/model.py | 1,264 | 4.03125 | 4 | class Point:
x: float
y: float
def __init__(self, x_init: float, y_init: float):
self.x = x_init
self.y = y_init
def __repr__(self):
return "".join(["Point(", str(self.x), ",", str(self.y), ")"])
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Point):
return (self.x == other.x) & (self.y == other.y)
return False
def __hash__(self):
return hash(str(self))
class Circle:
center: Point
radius: float
def __init__(self, x: float, y: float, r: float):
self.center = Point(x, y)
self.radius = r
def __repr__(self):
return "".join(["Circle(", str(self.center.x), ", ", str(self.center.y), ", ", str(self.radius), ")"])
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Circle):
return (self.center.x == other.center.x) & (self.center.y == other.center.y) & (self.radius == other.radius)
return False
class Trilateration:
sniffers: [Circle]
result: Circle
meta: []
def __init__(self, sniffers: [Circle], result: Circle = None):
self.sniffers = sniffers
self.result = result
|
86c7a06e64d5c57ca897d23a91b7df21d6a9c068 | shosato101/CheckiO_Missions | /simple/Sun_Angle.py | 1,558 | 3.6875 | 4 | # 要件
# 06:00から18:00までのあいだで、時刻に対応する太陽の角度を計算する。
# 太陽の角度は、06:00で0度、12:00で90度、18:00で180度とする。
# 角度は少数第二位まで求める。
# 範囲外の時刻である場合、"I don't see the sun!"という文字列を返す。
# 設計
# 単位を分に揃える。
# 06:00から18:00までの経過時間の比率と、0度から180度までの角度の比率を対応させる。
# 入力された時刻をもとに、太陽の角度を出力する。
def sun_angle(time):
t_deg = int(time[:2]) * 60 + int(time[3:]) - 360 # 06:00以降の時間経過分を算出する。
t_per = t_deg / 720 # 06:00~18:00までの12時間(720min)のうち、時間が何割経過しているかを求める。
sun_angle = round(180 * t_per, 2)
if 0 <= t_deg <= 720:
return sun_angle
else:
return "I don't see the sun!"
if __name__ == '__main__':
print("Example:")
print(sun_angle("07:00"))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert sun_angle("07:00") == 15
assert sun_angle("01:23") == "I don't see the sun!"
print("Coding complete? Click 'Check' to earn cool rewards!")
# 所感
# スライスの理解度が深まった。
# 関数やライブラリの知識より、要件を立式する力が求められる課題だった。
# 要件定義、問題の抽象化の大切さを体感した。
|
fe0c7a72001787bd4f4d2251d58dad5cc6755f0c | propython99/learn_python | /second_round/lists.py | 4,970 | 3.796875 | 4 | class Student:
pass
s1 = Student()
s2 = Student()
s3 = Student()
# print(type(s1))
# list properties:
# 1. ordered
# 2. mutable (changeable)
# 3. duplicates allowed
# english_scores = [ 10, 10, 10, 20, 10, 20, 20, 10, 20, 20]
###########################################
# int
# float
# bool
# str
# mixed_types = [10, "oranges", "fine", "mountains", True, False, 5.5, s1, s2]
###########################################
# print([ 10, 10, 10, 20, 10, 20, 20, 10, 20, 20])
# print(english_scores)
###########################################
# monthly_spending = [100, 200, 150]
# [150, 200, 100]
# jan = first item of monthly_spending
# feb = second item of monthly_spending
# mar = third item of monthly_spending
###########################################
# CRUD:
# 1. read
# 2. inserting
# 3. updating
# 4. deleting
###########################################
# main data structures in python:
# lists
# dictionaries
# # sets
# # tuples
###########################################
# english_scores = [ 10, 20, 25]
# [ 10, 20, 25]
# 0 1 2
# 1. read
# for first item:
# print(english_scores[0])
# 2nd item:
# print(english_scores[1])
# 3rd item:
# print(english_scores[2])
# Accessing range of items: For example, 2nd and 3rd items:
# print(english_scores[1:3]) # left value included, right value excluded
# print(english_scores[3]) # gives IndexError (list index out of range)
# 1:3
# 1, 2, not(3)
# If we want all items till the end starting in the middle:
# english_scores = [ 10, 10, 10, 20, 10, 20, 20, 10, 20, 20]
# print(english_scores[5:])
# If we want all items from the beginning of the list till some point in the middle:
# english_scores = [ 10, 11, 12, 28, 15, 21, 22, 9, 20, 7]
# print(english_scores[0:4]) # [ 10, 11, 12, 28]
# print(english_scores[:4]) # [ 10, 11, 12, 28]
# value order: 10, 11, 12, 28, 15, 21, 22, 9, 20, 7
# index order: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# 193
# 192
# 1:
# 0, 1, 2, 3,.....192 --> 193 elements
# # finding length of a list:
# english_scores = [ 10, 10, 10, 20, 10, 20, 20, 10, 20, 20]
# print(len(english_scores))
# english_scores = [ 10, 11, 12, 20, 17, 18, 16, 7, 8, 4, 24, 3]
# print all except first item in the list:
# print(english_scores[1:])
# print(english_scores[1:10])
# print(english_scores[1:len(english_scores)]) # because len(english_scores) evaluates to 10 for this list
# print(len(english_scores))
# english_scores = [ 10, 11, 12]
# # english_scores[len(english_scores)]
# length = len(english_scores)
# negative indexing (to help with navigating the list from the rear end of the list)
# value order: 10, 11, 12
# + index order: 0, 1, 2
# - index order: -3, -2, -1
# english_scores[0]
# english_scores[1]
# # print(english_scores[len(english_scores)-1]) # gives last item
# print(english_scores[-2]) # gives the last item
# print(english_scores[0])
# print(english_scores[-3])
# indexing of strings works the same way as lists
# fruit = "apple"
# # value order: a, p, p, l, e
# # positive index order: 0, 1, 2, 3, 4
# # negative index order: -5, -4, -3, -2, -1
# print(fruit[-3:])
# 2. inserting an item into a list
# first_list = [5, 28, 90]
# first_list.append(83)
# print(first_list)
# second_list = [73, 28, 50] # [5, 28, 90, 73, 28, 50]
# first_list.extend(second_list)
# print(first_list)
# first_list.append([73, 28, 50])
# print(first_list)
# first_list.append(73, 28, 50) # gives TypeError: append() takes exactly one argument (3 given)
# 3. updating
# first_list = [5, 28, 90]
# first_list[0] = 30
# 4. deleting
# first_list = [5, 28, 5, 90]
# first_list.remove(5)
# modified_list = first_list
# print(modified_list)
# # 5. sorting:
# a = {5,28,5,90, 78, 81, 38, 28, 39, 63, 73} # sets are not ordered
# print(a)
# a = [5,28,5,90, 78, 81, 38, 28, 39, 63, 73]
# a.sort(reverse=True)
# print(a)
# a = ["cherries", "apples", "bananas", "dragon fruit"]
# print(a)
# a.sort()
# print(a)
# a.sort(reverse=True)
# print(a)
# # 6. counting
# a = [5,28,5,90, 78, 81, 38, 28, 39, 63, 73]
# print(a.count(28))
|
5fdc6d68c1440f6a513f610be0c9a480432383eb | jayzane/leetcodePy | /linked_list/skip_list.py | 2,621 | 3.796875 | 4 | """
跳表
Redis的有序集合会用到
特点:
查找、删除、插入:O(log(n))
空间: O(n)
与红黑树比较:
查找、删除、插入都是O(log(n))
但是跳表 按照区间查找数据(比如查找值在[100, 356]之间的数据)比红黑树效率高
2020-12-18: 36.09.60;19.04.14;07:46.69;
2020-12-19: 06:51.10;
"""
import random
class SkipListNode:
def __init__(self, val, high):
self.val = val
self.deeps = [None] * high
def __repr__(self):
return 'Node(val={},deep={})'.format(self.val, len(self.deeps) - 1)
class SkipList:
_max_high = 4
def __init__(self):
self._high = 1
self._head = SkipListNode(None, self._max_high)
def random_high(self, p=0.25):
high = 1
while high < self._max_high and random.random() < p:
high += 1
return high
def find(self, val):
curr = self._head
for i in range(self._high - 1, -1, -1):
while curr.deeps[i] and curr.deeps[i].val < val:
curr = curr.deeps[i]
if curr.deeps[i] and curr.deeps[i].val == val:
return curr.deeps[i]
def insert(self, val):
if self._high == 1:
high = self._high = self._high + 1
else:
high = self.random_high()
if self._high < high and self._high < self._max_high:
high = self._high = self._high + 1
curr = self._head
new_node = SkipListNode(val, high)
for i in range(high - 1, -1, -1):
while curr.deeps[i] and curr.deeps[i].val < val:
curr = curr.deeps[i]
new_node.deeps[i] = curr.deeps[i]
curr.deeps[i] = new_node
def delete(self, val):
curr = self._head
for i in range(self._high - 1, -1, -1):
while curr.deeps[i] and curr.deeps[i].val < val:
curr = curr.deeps[i]
if curr.deeps[i] and curr.deeps[i].val == val:
curr.deeps[i] = curr.deeps[i].deeps[i]
def __repr__(self):
vals = []
for i in range(self._high - 1, -1, -1):
val = []
curr = self._head.deeps[i]
while curr:
val.append(str(curr.val))
curr = curr.deeps[i]
vals.append('-->'.join(val))
return str(vals)
if __name__ == '__main__':
s_list = SkipList()
for n in range(20):
s_list.insert(n)
pi = s_list.find(8)
print(pi)
print(s_list)
s_list.delete(10)
print(s_list)
s_list.delete(7)
print(s_list)
s_list.delete(5)
print(s_list)
|
d964be1451e21729893cc7468c364040f4cc5ddd | Mukesh-SSSDIIT/python2021_22 | /Sem5/Strings/string_2.py | 189 | 3.984375 | 4 | str = "Python"
print(str[0])
print(str[1],"\n")
for ch in str:
print(ch)
l = len(str)
print("\n")
for i in range(l):
print(str[i])
print("tho" in str)
print("the" in str) |
7e030c80c0ccd06514e626135cc4ae1f4160d06a | dylantzx/HackerRank | /30 Days Of Code/Interfaces.py | 661 | 3.9375 | 4 | ############################# Question ###########################
# https://www.hackerrank.com/challenges/30-interfaces/problem
##################################################################
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
primelist = []
for i in range(1,n+1):
if n%i==0:
primelist.append(i)
return sum(primelist)
n = int(input())
my_calculator = Calculator()
s = my_calculator.divisorSum(n)
print("I implemented: " + type(my_calculator).__bases__[0].__name__)
print(s) |
97a9a43808ce58cf7cd4357c75fc61fd67e6b8df | Ragib95/my_work | /Algorithm_coursera/fib.py | 353 | 3.65625 | 4 | # Uses python2
#def calc_fib(n):
# if (n <= 1):
# return n
#
# return calc_fib(n - 1) + calc_fib(n - 2)
#
#n = int(input())
#print calc_fib(n)
n = int(raw_input())
calc_fib = []
for i in range(0,n+1):
calc_fib.append(0)
if i <= 1:
calc_fib[i] = i
else:
a = i-1
b = i-2
calc_fib[i] = calc_fib[a] + calc_fib[b]
print calc_fib[n] |
94b591f620815a9027dd6e3a48be06f2edaa9297 | DaviMarinho/PythonCEV | /ex014.py | 297 | 4.1875 | 4 | #Exercício Python 014: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
tempc = float(input('Escreva a temperatura em graus Celsius:\n'))
tempf = ((tempc/5)*9)+32
print('A temperatura de {}ºC é de {:.2f}ºF!'.format(tempc, tempf)) |
171998fd4e97809e1502f4ae3aceb98c2ee70e39 | wiboon123/Quest_Master_board_game | /chooseCharacter.py | 2,447 | 3.921875 | 4 | import random
def chooseOne() :
choose = False
while (choose == False) :
print ('Please choose Number 1 - 5')
number = input()
if number == '1' or number == '2' or number == '3' or number == '4' or number == '5' :
number = int(number)
choose = True
return number
def p1_character() :
heros = ['Priest', "Magician", "Robot", "Swordman", "Demon"]
for i in range(0,5):
print((i+1),'.',heros[i])
chooseCharacter = chooseOne()
if chooseCharacter == 1 :
character = "Priest"
hp = 26
position = 14
status = 0
print("You are Priest HP 26")
elif chooseCharacter == 2 :
character = "Magician"
hp = 24
position = 50
status = 0
print("You are Magician HP 24")
elif chooseCharacter == 3 :
character = "Robot"
hp = 25
position = 83
status = 0
print("You are Robot HP 25")
elif chooseCharacter == 4 :
character = "Swordman"
hp = 23
position = 2
status = 0
print("You are Swordman HP 25")
else :
character = "Demon"
hp = 23
position = 31
status = 0
print("You are Demon HP 23")
return character, hp, position, status
def p2_character(player2) :
if player2 == '2Player' :
character, hp, position, status = p1_character()
else :
heros = ['Priest', "Magician", "Robot", "Swordman", "Demon"]
character = random.choice(heros)
if character == 'Priest' :
hp = 26
position = 14
status = 0
print ('Player2 is a Priest')
elif character == 'Magician' :
hp = 24
position = 50
status = 0
print ('Player2 is a Magician', )
elif character == 'Robot' :
hp = 25
position = 83
status = 0
print ('Player2 is a Robot', )
elif character == 'Swordman' :
hp = 23
position = 2
status = 0
print ('Player2 is a Swordman', )
elif character == 'Demon' :
hp = 23
position = 31
status = 0
print ('Player2 is a Demon', )
return character, hp, position, status |
d2527f53c99d1b7e70bc132f7b359bc7672bf45b | dlefcoe/daily-questions | /squareRoot.py | 3,013 | 4.40625 | 4 | '''
Given a real number n, find the square root of n. For example, given n = 9, return 3.
'''
def main():
''' the main routine '''
n = input('enter a number: ')
answer = squareRoot(n)
print(answer)
print('invoking second method')
rossSquareRoot(n)
def squareRoot(n):
''' square root of a number by iteration
parameters:
n: number to find square root of
return:
nOut: the square root of n
'''
n = float(n)
if n == 1:
return 1
if n < 1:
# make logical start guess for n < 1
guess = 2*n
for _ in range(1, 21):
if guess*guess > n:
guess = guess * 1.1
elif guess*guess < n:
guess = guess * 0.9
else:
return guess
for _ in range(1, 21):
if guess*guess > n:
guess = guess * 1.01
elif guess*guess < n:
guess = guess * 0.99
else:
return guess
for _ in range(1, 101):
if guess*guess > n:
guess *= 1.001
elif guess*guess < n:
guess *= 0.999
else:
return guess
return guess
# make a logical start guess for n > 1
guess = 0.1 * n
print('...first batch working...')
for i in range(1, 21):
# do process 100 times
if guess*guess > n:
#print(f'{guess} is too large {i}')
guess = 0.9*guess
elif guess*guess < n:
# print(f'{guess} is to small {i}')
guess = 1.1*guess
else:
#print(f'{guess} is correct {i}')
return guess
print('...second batch working...')
for j in range(1, 21):
# do process 100 times
if guess*guess > n:
#print(f'{guess} is too large {i} - {j}')
guess = 0.99*guess
elif guess*guess < n:
#print(f'{guess} is to small {i} - {j}')
guess = 1.01*guess
else:
#print(f'{guess} is correct {i} - {j}')
return guess
print('...third batch working...')
for k in range(1, 21):
# do process 100 times
if guess*guess > n:
#print(f'{guess} is too large {i} - {j} - {k}')
guess = 0.999*guess
elif guess*guess < n:
#print(f'{guess} is to small {i} - {j} - {k}')
guess = 1.001*guess
else:
#print(f'{guess} is correct {i} - {j} - {k}')
return guess
return guess
def rossSquareRoot(n):
n = float(n)
goal = n
iterations = 15
lower = 0
upper = goal
if n < 1:
upper = 1
for _ in range(iterations):
attempt = (lower + upper) / 2
if attempt * attempt < goal:
lower = attempt
else:
upper = attempt
print(attempt)
if __name__ == "__main__":
main()
pass |
01498e15676d84022fa7db7e630499c450c7970f | dodonator/TripleTrial | /Beispielimplementation/Stufe_2/karten_verleichen.py | 2,053 | 3.921875 | 4 | #!/usr/bin/env python3
print("Triple Triad")
print("Karten vergleichen")
# Die vier Werte der ersten Karte werden der Reihe nach eingegeben:
print("Bitte die vier Werte (1-10) der ersten Karte eingeben: ")
up1 = input("Oben: ")
down1 = input("Unten: ")
left1 = input("Links: ")
right1 = input("Rechts: ")
print()
# Die vier Werte der zweiten Karte werden der Reihe nach eingegeben:
print("Bitte die vier Werte (1-10) der zweiten Karte eingeben: ")
up2 = input("Oben: ")
down2 = input("Unten: ")
left2 = input("Links: ")
right2 = input("Rechts: ")
print()
# Die Werte werden in Integer umgewandelt:
up1 = int(up1)
down1 = int(down1)
left1 = int(left1)
right1 = int(right1)
up2 = int(up2)
down2 = int(down2)
left2 = int(left2)
right2 = int(right2)
# Die bessere Karte wird als Integer gespeichert
winner = 0
# Die Werte der beiden Karten vergleichen:
# Um zu vergleichen welche Karte besser ist, werden die Werte miteinander
# verglichen.
score_1 = up1 + down1 + left1 + right1
score_2 = up2 + down2 + left2 + right2
if score_1 > score_2:
winner = 1
up = str(up1)
down = str(down1)
left = str(left1)
right = str(right1)
number = 1
elif score_2 > score_1:
winner = 2
up = str(up2)
down = str(down2)
left = str(left2)
right = str(right2)
number = 2
if winner == 0:
print("Die Karten sind gleich gut.")
else:
print("Karte " + str(winner) + " war die bessere.")
# Die Ausgabe der Karten geschieht, wie bekannt:
width = 9
s_u = width // 2 - len(up) + 1
s_l = width // 2 - len(left)
s_r = width // 2 - len(right)
s_d = width // 2 - len(down) + 1
print() # Leerzeile
print("+" + width*"-" + "+") # Kopfzeile
print("|" + s_u*" " + up + (width//2)*" " + "|")
print("|" + width*" " + "|") # "leere" Zeile
print("|" + left + s_l*" " + str(number) + " "*s_r + right + "|")
print("|" + width*" " + "|") # "leere" Zeile
print("|" + s_d*" " + down + (width//2)*" " + "|")
print("+" + width*"-" + "+") # FußZeilen
print() # Leerzeile
|
a08c34ccb192222731b05d47c1f2306ce798ddc3 | QilinGu/DSAPractice | /L/FindLeavesBinaryTree.py | 649 | 3.75 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findLeaves(self, root):
self.result = []
self.dfs(root)
return self.result
def dfs(self, node):
if not node:
return 0
level = max(self.dfs(node.left), self.dfs(node.right)) + 1
if len(self.result) < level:
self.result.append([])
self.result[level-1].append(node.val)
node.val = None
return level
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print Solution().findLeaves(root) |
5877a16dc89493381df561c273dd2c6e9139cb13 | henryzt/ENGF0002 | /Misc/pong/pong_model.py | 23,751 | 3.53125 | 4 | # Simple Pong Game Model.
from math import pi,sqrt,cos,sin,tan,atan,inf
from random import Random
from abc import abstractmethod
from time import time
from pong_geometry import Point,Line,LineFactory,HalfPlaneFactory
from pong_settings import Direction,winning_score
#########
# Model #
#########
''' The Model class holds the game model, and manages the interactions
between the elements of the game. It doesn't display anything. '''
class Model():
# Initialisation
def __init__(self, controller, number_players=2):
self.controller = controller
self._init_constants()
self.init_game_objects(number_players)
self.restart()
def _init_constants(self):
self.canvas_width = self.controller.get_canvas_width()
self.canvas_height = self.controller.get_canvas_height()
self.distance_bar_bound = self.controller.get_distance_bar_bound()
self.bar_move_unit = self.controller.get_bar_move_unit()
def init_game_objects(self, number_players):
# Ball (initially placed in the middle of the screen)
self.ball = Ball()
self.ball_starting_point = Point(self.canvas_width/2,self.distance_bar_bound*8)
self.ball.set_position(self.ball_starting_point.X,self.ball_starting_point.Y)
self.controller.register_ball(self.ball)
# Walls
self.walls = [Wall(self.canvas_width/2,0,self.canvas_width), Wall(self.canvas_width/2,self.canvas_height,self.canvas_width)]
for wall in self.walls:
self.controller.register_wall(wall)
# Nets
self.nets = [Net(0,self.canvas_width/2,self.canvas_width-self.walls[0].get_thickness()*2,net_id=1),Net(self.canvas_width,self.canvas_height/2,self.canvas_height-self.walls[0].get_thickness()*2,net_id=2)]
for net in self.nets:
self.controller.register_net(net)
# Players' bars
self.bars = []
for i in range(1,number_players+1):
bar = Bar(i,self.bar_move_unit)
self.bars.append(bar)
self.controller.register_bar(bar)
self._set_initial_bar_positions()
# Players (initially empty, must be filled with set_players_info)
self.bots = dict()
self.local_players = dict()
self.remote_players = dict()
def set_players_info(self, players_info):
for (player_id,player_type) in players_info:
bar = self.bars[player_id-1]
if player_type == 'local':
self.local_players[player_id] = ManualPlayer(bar,self,is_local=True)
elif player_type == 'remote':
bar.set_color('red')
self.remote_players[player_id] = ManualPlayer(bar,self,is_local=False)
# switch control between players depending on the position of the ball
hf_factory = HalfPlaneFactory()
remote_player_halfplane = hf_factory.get_halfplane_containing_point(Line(1,0,-self.canvas_width/2),bar.get_central_point())
self.ball.set_remote_player_region(remote_player_halfplane)
else:
self.bots[player_id] = DumbBotPlayer(bar,self)
def restart(self):
self._set_initial_bar_positions()
self.score = [0,0]
self.controller.update_score(self.score)
self.kickoff_time = True
self.game_running = True
def _set_initial_bar_positions(self):
bars_positions = self._compute_initial_bar_positions()
i = 0
for bar_pos in bars_positions:
self.bars[i].set_position(bar_pos.X,bar_pos.Y)
i += 1
# NOTE: the following assumes only two players -- could be extended for more players
def _compute_initial_bar_positions(self):
return [Point(self.distance_bar_bound,self.canvas_height/2), Point(self.canvas_width-self.distance_bar_bound,self.canvas_height/2)]
# getter and setter methods
def get_ball(self):
return self.ball
def get_walls(self):
return self.walls
def get_canvas_width(self):
return self.canvas_width
def get_local_players(self):
return list(self.local_players.values()) + list(self.bots.values())
def set_score(self, new_score):
self.score = new_score
# dynamic methods
def kickoff_ball(self, init_angle=None):
self.last_ball_hitter = -1
if init_angle is not None:
self.ball.set_angle(init_angle)
self.ball.kickoff(self.ball_starting_point)
def move_local_player_bar(self, direction, is_local_player, player_id = None):
if is_local_player:
[player] = self.local_players.values()
player.move_bar(direction,self.walls)
# moving the bar may have caused a collision with the ball, we should check
self.check_ball(game_speed)
else:
raise RuntimeError("Model asked to move local player, but {} isn't a local player in {} nor a networked opponent in {}".format(player_id, self.local_players.keys(), self.remote_players.keys()))
def move_remote_player_bar_to_point(self, player_id, xpos, ypos):
if int(player_id) in self.remote_players:
self.remote_players[int(player_id)].move_bar_to(xpos, ypos)
else:
print("Model asked to move bar of remote player, but {} isn't a remote player -- i.e., not in {}".format(player_id, self.remote_players.keys()))
def _is_player_bar(self,bar):
return bar.get_id() > 0 and bar.get_id() < len(self.score)+1
def check_ball(self,game_speed):
if not self.ball.is_inplay:
return
self._check_ball_bouncing(game_speed)
self._check_ball_scoring(game_speed)
# NOTE: the following conditions should not happen
if self.ball.position.getX() < - self.ball.get_size()*2 or self.ball.position.getX() > self.canvas_width + self.ball.get_size()*2 or self.ball.position.getY() < 0 or self.ball.position.getY() > self.canvas_height:
self.ball.set_outofbound()
raise RuntimeError("Ball out of the screen!")
def _check_ball_bouncing(self,game_speed):
for bar in self.bars + self.walls:
new_angle = bar.get_bouncing_angle(self.ball,game_speed)
if new_angle != None:
print("Ball (at {}) bouncing from angle {} to new angle {}".format(self.ball.position,self.ball.get_angle(),new_angle))
self.ball.bounce(new_angle,self.controller.get_speed())
if self._is_player_bar(bar):
self.last_ball_hitter = int(bar.get_id())
return
def _check_ball_scoring(self,game_speed):
for net in self.nets:
if net.get_bouncing_angle(self.ball,game_speed)!= None:
print("Ball touched a net: updating score")
self.update_score(net.get_id())
self.ball.set_outofbound()
def update_score(self,net_id):
indices = self._select_player_indices_increasing_score(net_id)
for index in indices:
self._add_point(index)
def _select_player_indices_increasing_score(self,net_id):
indices = []
last_hitter = int(self.last_ball_hitter)-1
# normal case: somebody hit the ball beyond another player's bar
if last_hitter != int(net_id)-1:
indices = [last_hitter]
# own goal case: every other player earns a point
else:
indices = list(range(len(self.bars)))
indices.remove(last_hitter)
return indices
def _add_point(self,player_index):
if player_index >= 0 and player_index < len(self.score):
self.score[player_index] += 1
self.controller.update_score(self.score)
if self.score[player_index] == winning_score:
self.game_over()
def game_over(self):
if self.game_running:
self.game_running = False
self.controller.game_over()
def _extract_initial_ball_angle(self):
return Random().random() * pi/6 + pi/6 # set initial direction of the ball as random, within a reasonable angle
def _is_ball_at_halfcourt(self, speed):
return self.ball.get_position().X <= self.canvas_width/2 + speed or self.ball.get_position().X >= self.canvas_width/2 - speed
def update(self, game_speed):
if self.game_running:
if not self.ball.is_inplay():
self.kickoff_ball(self._extract_initial_ball_angle())
# move the ball, if it is not remotely controlled (or if it is close to be handed over to us)
if not self.ball.is_remotely_controlled() or self._is_ball_at_halfcourt(game_speed):
self.ball.move(game_speed)
self.check_ball(game_speed)
self.controller.update_score(self.score)
for bot in self.bots.values():
bot.act()
#################
# Model Objects #
#################
''' Class representing the ball. There must be only one ball per game, and it must not move if not in play.'''
class Ball():
def __init__(self):
self.inplay = False
self.radius = 20
self.position = Point(0,0)
self.angle = 0
self.remote_player_region = None
self.remotely_controlled = False
def get_size(self):
return self.radius
def get_position(self):
return self.position
def set_position(self,xpos,ypos):
self.position = Point(float(xpos),float(ypos))
def get_angle(self):
return self.angle
def set_angle(self, angle):
self.angle = angle
def set_remote_player_region(self,region):
self.remote_player_region = region
def is_remotely_controlled(self):
return self.remote_player_region != None and self.remote_player_region.contains(self.position)
def set_outofbound(self):
self.inplay = False
def is_inplay(self):
return self.inplay
def get_delta_future_position(self,speed):
ball_speed = 12 * speed
delta_x = ball_speed * cos(self.angle)
delta_y = ball_speed * sin(self.angle)
return delta_x,delta_y
def move(self,speed,angle=None):
if self.inplay:
if angle != None:
self.angle = angle
(delta_x, delta_y) = self.get_delta_future_position(speed)
self.position.move(delta_x,delta_y)
def bounce(self,new_angle,speed):
self.move(speed,new_angle)
def kickoff(self, point):
# don't put another ball in play
if self.inplay:
return
self.inplay = True
self.position = point.copy()
''' The GenericBar class implements methods common to all kinds of bars in the game (players' bats, walls, nets).'''
class GenericBar():
def __init__(self, xcenter, ycenter, size, inclination_angle_wrt_xaxis, thickness, color, bar_id):
self.size = size
assert inclination_angle_wrt_xaxis >= 0 and inclination_angle_wrt_xaxis < 2*pi
self.inclination = inclination_angle_wrt_xaxis
self.thickness = thickness
self.color = color
self.bar_id = bar_id
self.line_factory = LineFactory()
self.halfplane_factory = HalfPlaneFactory()
self.set_position(xcenter,ycenter)
def set_position(self,x,y):
self.x = x
self.y = y
self._update_bouncing_half_planes()
def get_xpos(self):
return self.x
def get_ypos(self):
return self.y
def get_central_point(self):
return Point(self.get_xpos(),self.get_ypos())
def get_max_dimension(self):
return max(self.get_size(),self.get_thickness())
def get_min_dimension(self):
return min(self.get_size(),self.get_thickness())
def get_size(self):
return self.size
def get_inclination(self):
return self.inclination
def get_thickness(self):
return self.thickness
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
def get_id(self):
return self.bar_id
# Methods to compute the lines corresponding to the bar edges
def _update_bouncing_half_planes(self):
self.bouncing_half_planes = [] # re-initialise the HalfPlane objects not containing the bar center
angles = [self.inclination,self.inclination-pi/2]
dimensions = [self.thickness,self.size]
for index in range(len(angles)):
for line in self._get_lines(angles[index], dimensions[index]):
new_bouncing_halfplane = self.halfplane_factory.get_halfplane_opposite_point(line,self.get_central_point())
self.bouncing_half_planes.append(new_bouncing_halfplane)
def _get_lines(self,angle,dimension):
lines = set([])
for extreme in self._get_central_extremes(self.x,self.y,angle,dimension):
lines.add(self.line_factory.get_line_from_point_and_inclination(extreme,angle))
return lines
def _get_central_extremes(self,x_center_bar_edge,y_center_bar_edge,angle,dimension):
ext1 = Point(x_center_bar_edge - dimension/2 * sin(angle),y_center_bar_edge + dimension/2 * sin(pi/2 - angle))
ext2 = Point(x_center_bar_edge + dimension/2 * sin(angle),y_center_bar_edge - dimension/2 * sin(pi/2 - angle))
return [ext1,ext2]
# Methods to compute if the ball should bounce and with which angle
'''Returns an angle if the ball has crossed one or more bar edges, None otherwise.'''
def get_bouncing_angle(self,ball,game_speed):
crossed_half_planes = []
ball_size = ball.get_size()
ball_angle = ball.get_angle()
ball_position = ball.get_position()
bouncing_planes_containing_ball = self.get_bouncing_half_planes(ball_position)
print("get_bouncing_angle, half planes ball is in: {}".format(bouncing_planes_containing_ball))
# if the ball is inside the bar (e.g., because the bar moved),
# bring the ball back outside
while len(bouncing_planes_containing_ball) == 0:
ball.move(game_speed, ball_angle - pi)
ball_position = ball.get_position()
bouncing_planes_containing_ball = self.get_bouncing_half_planes(ball_position)
# if the ball faces only one bouncing half plane from this bar,
# it should NOT bounce if it is getting farther away.
# The ball should instead bounce if either:
# (1) the ball would cross the bar's edge / half plane; OR
# (2) the distance of the ball to the bar's edge is lower than
# the ball size (e.g., because the bar moved)
if len(bouncing_planes_containing_ball) == 1:
[bhf] = bouncing_planes_containing_ball
line = bhf.get_line()
distance_ball_bhf = line.get_min_distance_to_point(ball_position)
(delta_x, delta_y) = ball.get_delta_future_position(game_speed)
ball_future_position = Point(ball_position.X + delta_x, ball_position.Y + delta_y)
future_distance_ball_bhf = line.get_min_distance_to_point(ball_future_position)
if (bhf.contains(ball_position) and not bhf.contains(ball_future_position)) or (distance_ball_bhf <= ball.get_size()):
crossed_half_planes = [bhf]
# move the ball fully outside the bar
self._move_ball_outside_bar(ball,line,game_speed)
# if the ball is inside more than one bouncing half planes,
# it means it is closer to a bar's corner rather than to any
# bar's edge. So, we check that the distance of the ball
# center to all bar's corner is smaller than the ball's size
elif len(bouncing_planes_containing_ball) == 2:
[bp1,bp2] = bouncing_planes_containing_ball
corner = bp1.get_line_intersection(bp2)
if corner.distance(ball_position) < ball.get_size():
crossed_half_planes = bouncing_planes_containing_ball
# it shouldn't be possible for the ball to face more than
# two bar's edges
else:
raise RuntimeError("Ball ({},{}) facing an unexpected number of edges in Bar {}: {}".format(ball.get_position(),ball.get_angle(),self.get_id(),bouncing_planes_containing_ball))
# return the bouncing angle
print("\nFound intersected bar's edges: {}".format(crossed_half_planes))
return self._get_new_angle(crossed_half_planes,ball_angle)
def _get_min_distance_from_bar_extreme(self,ball_position):
# NOTE: we could store extremes (and update them when move)
# instead of recomputing them every time
min_dist = inf
angles=[self.inclination,self.inclination-pi/2]
dimensions=[self.thickness,self.size]
for index in range(2):
for extreme in self._get_central_extremes(self.x,self.y,angles[index],dimensions[index]):
new_dist = ball_position.distance(extreme)
min_dist = min(min_dist,new_dist)
return min_dist
def get_bouncing_half_planes(self,ball_center_position):
matching_half_planes = []
for hf in self.bouncing_half_planes:
if hf.contains(ball_center_position):
matching_half_planes.append(hf)
return matching_half_planes
def _move_ball_outside_bar(self,ball,edge_line,game_speed):
ball_angle = ball.get_angle()
while True:
distance_ball_bhf = edge_line.get_min_distance_to_point(ball.get_position())
if distance_ball_bhf > ball.get_size():
return
ball.move(game_speed, ball_angle - pi)
print("Moved the ball backwards.\nBall angle: {}, new ball position: {}, new distance: {}".format(ball.get_angle(),ball.get_position(),distance_ball_bhf))
def _get_new_angle(self,crossed_half_planes,initial_angle):
if len(crossed_half_planes) == 0:
return None
elif len(crossed_half_planes) == 1:
edge_inclination = crossed_half_planes[0].get_xaxis_inclination_angle()
angle_wrt_bar = initial_angle + edge_inclination
new_angle_wrt_bar = - angle_wrt_bar
new_angle = new_angle_wrt_bar - edge_inclination
# avoid angles which are too vertical
if int(new_angle / (pi/2)) % 2 == 1 and new_angle % (pi/2) < pi/10:
new_angle += pi / 10
return new_angle
# implements perfect reflection if the ball impacts two bar edges (i.e., a corner)
return initial_angle + pi
''' A wall represent a fixed surface (at the top and bottom of the screen in a two-player game) against which the ball would bounce. '''
class Wall(GenericBar):
def __init__(self, wall_xcenter, wall_ycenter, wall_length, wall_inclination=0, wall_thickness=30, wall_color="gray"):
super().__init__(xcenter=wall_xcenter, ycenter=wall_ycenter, size=wall_length, inclination_angle_wrt_xaxis=wall_inclination, thickness=wall_thickness, color=wall_color, bar_id=-1)
def get_width(self):
return self.size
def get_height(self):
return self.thickness
''' A net represents the surface behind (and protected by) a player. '''
class Net(GenericBar):
def __init__(self, net_xcenter, net_ycenter, net_length, net_inclination=pi/2, net_thickness=20, net_color="white",net_id=-2):
super().__init__(xcenter=net_xcenter, ycenter=net_ycenter, size=net_length, inclination_angle_wrt_xaxis=net_inclination, thickness=net_thickness, color=net_color, bar_id=net_id)
# ball doesn't bounce against a net
def get_bouncing_angle(self,ball,game_speed):
if super().get_bouncing_angle(ball,game_speed) != None:
return ball.get_angle()
return None
# don't mind move the ball backwards when it hits a net
def _move_ball_outside_bar(self,ball,edge_line,game_speed):
pass
''' Bars represent players' bats (name of the class could have been more explicit, actually).'''
class Bar(GenericBar):
def __init__(self, player_id, move_unit, bar_xcenter=0, bar_ycenter=0, bar_height=100, bar_width=20, bar_color="blue"):
super().__init__(xcenter=bar_xcenter, ycenter=bar_ycenter, size=bar_height, inclination_angle_wrt_xaxis=pi/2, thickness=bar_width, color=bar_color, bar_id = player_id)
self.move_unit = move_unit
def get_move_unit(self):
return self.move_unit
def get_width(self):
return self.thickness
def get_height(self):
return self.size
''' move due to user input '''
def move_bar(self, direction, walls_array):
wall_margin = walls_array[0].get_height()/2
max_wall_height = max([w.get_ypos() for w in walls_array])
new_y = self.y
# NOTE: the following only works for vertical bars -- could be extended to multi-player games, relatively easily
if direction == Direction.UP:
new_y -= min(self.move_unit, self.y - self.get_height()/2 - wall_margin)
elif direction == Direction.DOWN:
new_y += min(self.move_unit, max_wall_height - wall_margin - self.y - self.get_height()/2)
self.set_position(self.x,new_y)
###########
# Players #
###########
''' Abstract class for players '''
class AbstractPlayer():
def __init__(self, own_bar, model):
self.bar = own_bar
self.model = model
def get_bar(self):
return self.bar
@abstractmethod
def get_type(self):
pass
''' Abstract class modeling a player managed by computer '''
class AbstractBotPlayer(AbstractPlayer):
@abstractmethod
def act(self):
pass
def get_type(self):
return "bot"
''' Computer player implementing a simple strategy '''
class DumbBotPlayer(AbstractPlayer):
def __init__(self, own_bar, model):
super().__init__(own_bar, model)
self.last_move_time = time()
self.move_frequency = 0.05
# NOTE: decreasing the move_frequency variable makes bot players slower, and hence low delay over network games more and more important
# Main method: the bot player tries to align its bar to the ball (only a very dumb strategy is implemented)
def act(self):
ball = self.model.get_ball()
walls = self.model.get_walls()
# skip if we moved shortly before (regulates the number of moves that the bot can do)
curr_time = time()
if curr_time - self.last_move_time < self.move_frequency:
return
# skip if ball is far away
ball_distance = self.bar.get_central_point().distance(ball.get_position())
if ball_distance > self.model.get_canvas_width()/3:
return
# otherwise, try to match ball's position
if self.bar.get_ypos() - self.bar.get_height()/2 > ball.get_position().Y:
self.bar.move_bar(Direction.UP,walls)
elif self.bar.get_ypos() + self.bar.get_height()/2 < ball.get_position().Y:
self.bar.move_bar(Direction.DOWN,walls)
self.last_move_time = time()
''' Class modeling non-computer players -- e.g., manually controlled by the user or network opponents '''
class ManualPlayer(AbstractPlayer):
def __init__(self, own_bar, model, is_local):
super().__init__(own_bar, model)
self.type_desc = 'local'
if is_local:
self.type_desc = 'remote'
def move_bar(self, direction, walls_array):
self.bar.move_bar(direction, walls_array)
def move_bar_to(self, xpos, ypos):
self.bar.set_position(xpos, ypos)
def get_type(self):
return self.type_desc
|
09f7566f35a8da98f2daccac3378399bfb88619e | MBCook/IttyBittyCity | /Backup/2005/01 - January/31/ObjectCollection.py | 2,371 | 3.5625 | 4 | class ObjectCollection:
"""Holds objects, gives out handles, and can be used to look up handles."""
def __init__(self):
"""Prepare the object collection to hold stuff."""
self.nextID = 1
self.objects = {}
def addObject(self, newObject):
"""Add an object to the collection and return a handle."""
self.objects[nextID] = newObject
self.nextID = self.nextID + 1
return self.nextID - 1
def deleteObject(self, objectHandle):
"""Remove an object from the collection."""
del self.objects[objectHandle]
def clearCollection(self):
"""Remove EVERYTHING from the collection."""
self.objects.clear()
def checkHandle(self, objectHandle):
"""Check to see if the handle is valid."""
return self.objects.has_key[objectHandle]
def retrieveObject(self, objectHandle):
"""Return the object for the given handle."""
if self.objects.has_key(objectHandle):
return self.objects[objectHandle]
else:
return None
def retrieveAllInClass(self, classHandle):
"""Retrieve all objects in a class."""
if len(self.objects) == 0:
return None
if classHandle == None:
return self.objects.values()
self.objectsInClass = []
for object in self.objects.values():
if object.getClass() == classHandle:
self.objectsInClass.append(object)
return self.objectsInClass
def retrieveAllInSubclass(self, classHandle, subclassHandle):
"""Retrieve all objects in a subclass."""
if len(self.objects) == 0:
return None
if classHandle == None:
return self.objects.values()
self.objectsInClass = self.retrieveAllInClass(classHandle)
if subclassHandle == None:
return self.objectsInClass
self.objectsInSubclass = []
if self.objectsInClass == None:
return None
if len(self.objectsInClass) == 0:
return None
for object in self.objectsInClass:
if object.getSubclass() == subclassHandle):
self.objectsInSubclass.append(object)
return self.objectsInSubclass
|
ea307fa20808211c01a50746ef10e576e732b32b | atm1992/algorithm_interview | /a5_quick_sort.py | 745 | 4.125 | 4 | # -*- coding: UTF-8 -*-
"""
快速排序。不稳定排序
默认使用第一个元素作为基准值,然后将数列切成两半,再递归处理。分治法
"""
def quick_sort(alist):
if not alist or len(alist) < 2:
return alist
mid = alist[0]
left_li = [x for x in alist[1:] if x <= mid]
right_li = [x for x in alist[1:] if x > mid]
left = quick_sort(left_li)
right = quick_sort(right_li)
return left + [mid] + right
if __name__ == '__main__':
alist = [2, 1, 45, 1, 21, 4, 2, 6, 9]
print("快速排序前:", alist)
# 这里与之前的排序不一样,这里是返回一个排好序的新列表,原列表没有改变
res = quick_sort(alist)
print("快速排序后:", res)
|
a01fa248c6b2caeaec983411f57829680ada4740 | chri89k9/chri89k9.github.io | /adventCalender/day1.py | 966 | 3.71875 | 4 | # https://adventofcode.com/2020/day/1
lines = [
'1721',
'979',
'366',
'299',
'675',
'1456',
]
def load_data(fileName):
global lines
with open(fileName, "r") as input_data:
lines = input_data.readlines()
for i in range(len(lines)):
lines[i] = lines[i].strip()
def problemOne():
global lines
# print(lines)
for aStr in lines:
for bStr in lines:
a = int(aStr)
b = int(bStr)
y = a + b
if y == 2020:
print(a,b,y, a*b)
return
def problemTwo():
for aStr in lines:
for bStr in lines:
for cStr in lines:
a = int(aStr)
b = int(bStr)
c = int(cStr)
y = a + b + c
if y == 2020:
print(a,b,c,y, a*b*c)
return
load_data("Day1-input.txt")
problemOne()
problemTwo()
|
46a33672fa01261cfc6a11442002e7e7726998a2 | bartdob/codeW | /decimal_endNumber.py | 395 | 4.28125 | 4 | Write a function that returns only the decimal part of the given number.
You only have to handle valid numbers, not Infinity, NaN, or similar. Always return a positive decimal part.
-------------------------------------
Solution
def get_decimal(n):
if n>0:
b=n-int(n)
elif n == 0:
b=0
else:
b=-(n-int(n))
print (b)
get_decimal(10)
get_decimal(1.2)
|
b30315fd43a5da9b2c608b599305ac6354f50981 | gabreuvcr/curso-em-video | /mundo2/ex039.py | 589 | 4.09375 | 4 | ## EX039 ##
from datetime import date
ano = int(input('Informe o seu ano de nascimento: '))
atual = date.today().year
idade = atual - ano
print('Quem nasceu em {} tem {} anos em {}.'.format(ano, idade, atual))
if idade < 18:
print('Ainda falta(m) {} ano(s) para o alistamento.'.format(18 - idade))
print('Seu alistamento será em {}'.format((18 - idade) + atual))
elif idade > 18:
print('Você já deveria ter se alistado há {} ano(s).'.format(idade - 18))
print('Seu alistamento foi em {}'.format(atual - (idade - 18)))
else:
print('É a hora de você se alistar!')
|
032f9929d5da4dcd957db169af707bab83f2b9bb | mindajalaj/academics | /Projects/python/pyh-pro/change_directory.py | 487 | 3.640625 | 4 | import os
import sys
globe=5
os.system("clear");
while globe==5:
print("\t1.To Change Directory");
print("\t2.To return Back");
choice=int(input("Enter your choice:"));
if choice==1:
y=input("\tEnter Destination_Location ...example : /root/Desktop/ :");
k=os.system("cd "+y);
if k==0:
print("\tDirectory Successfully changed...\n\n");
else:
print("\tDirectory Changing Failed...\n\n");
elif choice==2:
sys.exit();
else:
print("Invalid Choice");
|
2b7689f3b480756cce77d09d188e4c2fc2193790 | Anisha-Vulli/CSPP---1 | /CSSP-1 Practice/m8/Is In Exercise/is_in.py | 791 | 3.890625 | 4 | '''
Author: Anisha Vulli
Date: 07 Aug 2018
'''
def isIn_2(char_in,a_Str):
sorted_aStr = sorted(a_Str)
x = isIn(0,len(sorted_aStr),char_in,sorted_aStr)
return x
def isIn(min_val,max_val,char,a_Str):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
mid = (min_val+max_val)//2
if a_Str[mid] == char:
return "True"
elif mid == min_val or mid == max_val:
return "False"
else:
if a_Str[mid] > char:
return isIn(min_val,mid,char,a_Str)
elif a_Str[mid] < char:
return isIn(mid,max_val,char,a_Str)
def main():
data = input()
data = data.split()
print(isIn_2(data[0], data[1]))
if __name__ == "__main__":
main() |
38596622b30c78965d617f63133bb0d4a350b44b | lih627/python-algorithm-templates | /LeetCodeSolutions/LeetCode_0019.py | 509 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
left = head
right = head
while n > -1:
if not right:
return head.next
right = right.next
n -= 1
while right:
left, right = left.next, right.next
left.next = left.next.next
return head
|
56734a6dfd53dc29c3cbaa29d99e51180b2c851d | pavankumarag/ds_algo_problem_solving_python | /practice/medium/_29_min_max_binary_heap_construction.py | 1,754 | 3.875 | 4 |
def heapify_max(arr, n, i):
'''
To max heapify a subtree rooted with node i which is an index in arr[]. N is size of heap
'''
largest = i # Initialize largest as root
l = 2 * i + 1 # left child = 2*i + 1
r = 2 * i + 2 # right child = 2*i + 2
# If left child is larger than root
if l<n and arr[l] > arr[largest]:
largest = l
# If right child is larger than largest so far
if r<n and arr[r] > arr[largest]:
largest = r
if largest != i: # If largest is not root
arr[i], arr[largest] = arr[largest], arr[i]
heapify_max(arr, n, largest)
def heapify_min(arr, n, i):
'''
To min heapify a subtree rooted with node i which is an index in arr[]. N is size of heap
'''
smallest = i # Initialize smallest as root
l = 2 * i + 1 # left child = 2*i + 1
r = 2 * i + 2 # right child = 2*i + 2
# If left child is lesser than root
if l<n and arr[l] < arr[smallest]:
smallest = l
# If right child is lesser than smallest so far
if r<n and arr[r] < arr[smallest]:
smallest = r
if smallest != i: # If smallest is not root
arr[i], arr[smallest] = arr[smallest], arr[i]
heapify_min(arr, n, smallest)
def build_max_heap(arr, n):
start_index = int((n/2)) - 1 # Index of last non-leaf node
for i in range(start_index, -1, -1):
heapify_max(arr, n, i)
def build_min_heap(arr, n):
start_index = int((n/2)) - 1 # Index of last non-leaf node
for i in range(start_index, -1, -1):
heapify_min(arr, n, i)
def print_heap(arr, n):
print "Array representation of heap"
for i in range(n):
print arr[i],
print
if __name__ == "__main__":
arr = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17]
n = len(arr)
build_max_heap(arr, n)
print_heap(arr, n)
arr = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17]
build_min_heap(arr, n)
print_heap(arr, n) |
28f0128f4d8431ce47a558256c0d56103ac77ef0 | sangeethathankachan/numpy | /ndappend.py.py | 179 | 3.515625 | 4 | import numpy as np
a=np.arage(5)
print("array ",a)
print("shape ",a.shape)
b=np.arange(8,12)
print("array ",b)
print("shape ",b.shape)
c=np.append(a,b)
print("appended array ",c)
|
846639666299f6691b378da90bb3285a86a1460f | Babnik21/Euler | /Euler 5.py | 525 | 3.515625 | 4 | #ker potrebujemo le za števila do 20, za več ni smiselno
def na_prafaktorje(n):
i = 2
prafaktorji = []
while n != 1:
while n%i == 0:
prafaktorji.append(i)
n = n//i
i += 1
return prafaktorji
#z zgornjo funkcijo poiščemo prafaktorje vsake od prvih 20 števil in jih zapišemo v seznam (hitreje je na roke kot pisati program)
prafaktorji = [2, 2, 2, 2, 3, 3, 5, 7, 11, 13, 17, 19]
rezultat = 1
for el in prafaktorji:
rezultat = rezultat * el
print(rezultat)
|
06e6116bbd1324dae2157806c494234d8acfeb0e | She-Codes-Now/Intro-to-Python-MESA | /Web Dev Examples/movie-trailers/readXML.py | 1,724 | 3.9375 | 4 | from xml.dom.minidom import parse
import xml.dom.minidom
import media
def readMoviesXML(filename):
'''
This method takes an XML file as input, parses it and returns a list of
movie class objects. It uses DOM parser for XML processing. Other parsers
available in the Python library can also be used instead.
Assumptions
1: "filename" is a valid XML file (error conditions not handled)
'''
# List of movie objects
movieClassList = []
# Create a DOM tree
tree = xml.dom.minidom.parse(filename)
# Get the document from the tree
document = tree.documentElement
# Get all the movies from the XML file
movies = document.getElementsByTagName("movie")
# For each movie in the XML file,
# 1. get all tags for the given movie
# 2. create a movie class object
# 3. add the movie to the movie list
# [0] is used as we take only first child here
for movie in movies:
title = movie.getElementsByTagName('movie_title')[0]
movie_storyline = movie.getElementsByTagName('movie_storyline')[0]
poster_image = movie.getElementsByTagName('poster_image')[0]
trailer_youtube = movie.getElementsByTagName('trailer_youtube')[0]
movieClassList.append(media.Movie(title.childNodes[0].data,
movie_storyline.childNodes[0].data,
poster_image.childNodes[0].data,
trailer_youtube.childNodes[0].data))
# return the list of Movie objects extracted from the XML
return movieClassList
# For testing purpose only
# a = readMoviesXML("movies.xml")
# for m in a:
# m.printMovieDetails()
|
8cd1fb48fc7ec2b86c4d656d9a7a473a58d6ec89 | init-fun/Leetcode-prep | /Pattern-matching/X Unorganized/3sum.py | 869 | 3.5625 | 4 | def threesum(arr, target):
res = []
arr.sort() # O(nlogn)
for i, val in enumerate(arr):
if i > 0 and arr[i - 1] == val:
continue
left = i + 1
right = len(arr) - 1
while left < right:
new_sum = val + arr[left] + arr[right]
if new_sum > target:
right -= 1
elif new_sum < target:
left += 1
else:
res.append([val, arr[left], arr[right]]) # we got our triplet
left += 1
# removing duplicate
fptr = 0
sptr = 1
while sptr < len(res):
if res[sptr] == res[sptr - 1]:
fptr += 1
sptr += 1
return res[fptr:]
arr = [-3, 0, 1, 2, -1, 1, -2]
target = 3
arr = [-3, 0, 1, 2, -1, 1, -2]
target = 0
print(threesum(arr, target)) |
2f4df5ed96cd8ae577940c07f4667b7fab372413 | avaziyi/python_basic1 | /class_1.py | 516 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 17 23:33:17 2013
@author: Mars
"""
class Fruit(object):
def __init__(self,name,color,taste,poison):
self.name = name
self.color = color
self.taste = taste
self.poison = poison
def describe(self):
print "I am %s %s, it tastes %s." % (self.color,self.name,self.taste)
def is_edible(self):
if not self.poison:
print "OK,i am edible"
else:
print "Do not eat me!"
apple = Fruit("apple","red","delicious",False)
apple.describe()
apple.is_edible() |
74fb9d65ddeb2579c669f0741fbe44a632b5a7db | Rumate911/PYTHON_18022020_2 | /ua/univer/base/task_if/task_5.py | 789 | 3.78125 | 4 | def construction_more_1(x):
x = int(input("Введите значени: "))
if x>20:
print("hello in club")
else:
print("go home")
def construction_2_3(a):
if a > 0:
print("Result + number", a + 1)
elif a < 0:
print("Result - number", a - 2)
else:
print("Result 0 number", a + 10)
def construction_more_4(a,b,c):
x = 0
if a > 0:
x += 1
if b > 0:
x += 1
if c > 0:
x += 1
print("Result", x)
def construction_more_less_5(a, b, c):
x = 0
y = 0
if a > 0:
x += 1
elif a < 0:
y += 1
if b > 0:
x += 1
elif b < 0:
y += 1
if c > 0:
x += 1
elif c < 0:
y += 1
print("Result +", x )
print("Result -", y ) |
f142a713ff107e0d9db42f5e843d3056eeb71761 | zhankq/pythonlearn | /fenkpython/05/5.6/5.py | 122 | 3.859375 | 4 | def fn(n):
sum = 0
for i in range(1,n+1):
sum += pow(i,3)
else:
return sum
f = fn(3)
print(f) |
93083dca0579af9124512d310f6fafe70c17a7aa | Tman30/Hackerrank_Python_Practice_Problems_Submission | /Itertools/itertools.combinations().py | 284 | 3.65625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import combinations
if __name__ == '__main__':
string,r = input().split()
for j in range(int(r)):
for i in combinations(sorted(string),int(j+1)):
print("".join(i)) |
543197174bd0c57134ec18c673b276abadc06438 | dreisers/python | /section03/04-while.py | 310 | 3.875 | 4 | # /section03/04-while.py
# 반복문
x = 1
while x<=10:
print("x=%d" % x)
x += 1
#7단 출력하기
y = 1
while y<10:
z = 7 * y
print("7 * %d = %d" % (y,z))
y += 1
#1~10까지의 총합을 구하시오
x = 1
sum = 0
while x<=10:
sum += x
print('x=%d, sumg=%d' %(x,sum))
x += 1 |
db9aac2b81221e9e0d174c4c34be8e0e63481abe | CuriousG102/ipdConflict | /models/countryYear.py | 4,141 | 3.828125 | 4 | # Entries works as follows:
# Requests: Client requests an entry based on primary key (corresponds to row). Entries instantiates a Location class from the spreadsheet passed to it using gData representing the request and returns it to the client. Client can do what they wish with this class.
# Writes: Client decides to write a new entry by creating an instance of the Location class. Once they are ready to write it, they pass it to a method of Entrieswhich commits it to the spreadsheet.
# After fiddling and consideration, the decision was made to make a class called Spreadsheet. This class will have all of the methods required to perform the tasks of entries, but will conveniently allow for another layer of abstraction. Spreadsheets might use a CSV as a storage medium, an SQL database, a google doc, or anything else imaginable. The idea is that the storage medium can easily be changed without the need to make extensive modifications to the rest of the program
# pk starts at 2
from spreadsheets import Spreadsheet
from locations import Location
class Entries:
def __init__(self, country, year, entryPath): # complete
spreadsheetID = entryPath + "ipdConflict" + country + str(year)\
+ '.csv'
self.table = Spreadsheet()
if self.table.isPresent(spreadsheetID):
self.table.open(spreadsheetID)
else:
self.table.make(spreadsheetID)
def getNumEntries(self): # complete
return self.table.numRows() - 1 # return number of rows - 1 (excluding column labels)
def getEntry(self, pk): # complete
if pk > self.table.numRows() or pk < 2: # if the primary key is out of bounds, raise exception
raise ValueError("pk out of bounds")
row = self.table.getRow(pk)
entry = self.__processRow(row)
return entry
def makeEntry(self, location): # complete
row = self.__getRow(location)
self.table.append(row)
def changeEntry(self, pk, location): # complete
if self.table.numRows() < pk or pk < 2:
raise ValueError("pk out of bounds")
rowNumToChange = pk
entry = self.__getRow(location)
self.table.modify(rowNumToChange, entry)
def __getRow(self, location): # complete
# make an array of items to insert into row, pass that array to spreadsheet while specifying row
# order: resource, minetype, locationname, stdmeasure, annlLocCapacity in stdMeasure
# Jan ppu, yrlLocValue, capOfLocInKg, ppKilogram, long, lat, precisCode
# arbit field 1, arbit field 2, ...
row = []
row.extend([location.getResource(), location.getMineType(), location.getLocationName()])
row.extend([location.getStdMeasure(), location.getAnnlLocCapacity()])
row.extend([location.getPpu(), location.getYrlyLocValue()])
row.extend([location.getKgCapacity(), location.getPpk(), location.getLong()])
row.extend([location.getLat(), location.getPrecisCode()])
# must implement arbit fields!!
arbitFields = location.getArbitFields()
keys = arbitFields.keys().sort()
if keys != None:
for key in keys:
row.extend(key + '!' + arbitFields[key])
return row
def __processRow(self, row): # complete #given row, returns location
locToReturn = Location()
l = locToReturn
functionsToCall = [l.setResource, l.setMineType, l.setLocName, l.setStdMeasure,\
l.setAnnlLocCapacity, l.setPpu, l.setLongLat, l.setPrecisCode]
i = 0
while i <= 5:
functionsToCall[i](row[i])
i += 1
l.setLongLat(row[9], row[10])
l.setPrecisCode(row[11])
i = 12
while i < len(row):
arbitKeyValue = row[i]
key, value = arbitKeyValue.partition('!')[0], arbitKeyValue.partition('!')[2]
l.setArbitField(key, value)
return locToReturn
def save(self):
self.table.save()
def close(self):
self.table.close()
|
67973c76189b42265514a8b1f9d3b186078c234c | jaspereb/cloudLight | /Old Code/testOWMParse.py | 1,942 | 3.578125 | 4 | from urllib2 import Request, urlopen, URLError
import json
import datetime
import pytz
#For reference
#API_KEY = 74e3781521968a538eb598a44d263091
#CITY_ID = 6619279
#Defines
#Set to get new weather
updateWeather = 1;
weatherState = 0;
#0 - sunny/cloudy
#1 - rain
#2 - weird
#3 - storms
#4 - extreme
local = pytz.timezone ("Australia/Sydney")
#Program
request = Request('http://api.openweathermap.org/data/2.5/forecast?id=6619279&APPID=caa3c1d9fcc87e07420d987dbdaa99ab')
try:
if(updateWeather):
response = urlopen(request)
weatherJSON = response.read()
except URLError, e:
print 'URL Error while fetching weather. Got an error code:', e
parsedWeather = json.loads(weatherJSON)
#for key, value in parsedWeather.items():
# print("Key:")
# print(key)
# print parsedWeather[key]
weather = parsedWeather['list']
for hourly in range(0,len(weather)):
currentWeather = weather[hourly]
#Calculate if current weather period is <12 hours away (time is in UTC)
if (currentWeather['dt'] - time.time()) < 43200:
print("adding weather")
print(currentWeather['dt_txt'])
else:
print("ignoring weather")
print(currentWeather['dt_txt'])
continue
IDCode = currentWeather['weather'][0]['id']
IDFirst = IDCode/100
if(IDCode/10 == 90):
print("Extreme weather")
weatherState = 4
elif(IDFirst == 2):
print("Storms")
weatherState = 3
elif(IDFirst == 6 or IDFirst == 7):
print("Wierd Weather")
weatherState = 2
elif(IDFirst == 5):
print("Rain")
weatherState = 1
elif(IDFirst == 8 or IDFirst == 3 or IDFirst == 9 or IDCode == 800 or IDCode == 500)
print("Clear")
weatherState = 0
else:
print("Unrecognised Weather!")
weatherState = 5
# print('Weather at time ' + ' is:')
# print(utc_dt)
#parsedList = json.loads(parsedWeather['list']) |
f3d5a087e9b851f622161239b754f7fba33515cd | Mazhar004/algo-in-python | /data_structure/stack/Stack_test.py | 493 | 3.859375 | 4 | from Stack import Stack
stack = Stack()
while True:
try:
t = int(input(
'Press 1 to push\nPress 2 to pop\nPress 3 to peek\nPress Enter to exit\n= '))
if t == 1:
data = map(int, (input('Enter space seperated values = ').split()))
for i in data:
stack.push(i)
elif t == 2:
print(stack.pop())
elif t == 3:
print(stack.peek())
else:
break
except:
break
|
0b80f24ce87d8662d96ffb718da87a25f88bafbf | frankie-s/Python_Course | /money_bags.py | 15,647 | 3.640625 | 4 | import os
import csv
__author__ = 'frankie'
class Bank:
def __init__(self, name):
self._name = name
self._accounts = {}
def save(self):
writer = csv.writer(open('transaction_log.csv', 'ab'))
for k in self._accounts.items():
writer.writerow([k[0], k[1].owner, k[1].acct_name, k[1].p, k[1].n, k[1].di, k[1].q, k[1].h, k[1].do, k[1].bug])
@property
def largest(self):
total_lst = []
name_lst = []
for key, val in self._accounts.items():
print("Account Name: {1} \t Balance: {0:>5.2f} USD".format(self._accounts[key].balance, self._accounts[key].acct_name))
total_lst.append(self._accounts[key].balance)
name_lst.append(self._accounts[key].acct_name)
return name_lst[total_lst.index(max(total_lst))]
@property
def grand_total(self):
gt = 0
for key in self._accounts:
gt += self._accounts[key].balance
return gt
class Account:
current_acct_nu = 100
def __init__(self, owner, acct_name, p, n, di, q, h, do, bug_out):
self._owner = owner
self._acct_name = acct_name
self._bug_out = bug_out
self._p = p
self._n = n
self._di = di
self._q = q
self._h = h
self._do = do
self._balance = 0
def deposit(self, p, n, di, q, h, do):
self._p += p
self._n += n
self._di += di
self._q += q
self._h += h
self._do += do
self._add = p * .01 + n * .05 + di * .10 + q * .25 + h * .50 + do * 1.00
return self._add
def withdraw(self, p, n, di, q, h, do):
self._p -= p
self._n -= n
self._di -= di
self._q -= q
self._h -= h
self._do -= do
self._remove = p * .01 + n * .05 + di * .10 + q * .25 + h * .50 + do * 1.00
return self._remove
@property
def owner(self):
return self._owner
@property
def acct_name(self):
return self._acct_name
@property
def bug(self):
return self._bug_out
@property
def p(self):
return self._p
@property
def n(self):
return self._n
@property
def di(self):
return self._di
@property
def q(self):
return self._q
@property
def h(self):
return self._h
@property
def do(self):
return self._do
@property
def balance(self):
return (self._p * .01) + (self._n * .05) + (self._di * .10) + (self._q * .25) + (self._h * .50) + (self._do * 1.00)
def main():
os.system('cls' if os.name == 'nt' else 'clear')
my_bank = Bank("First Bank of Matratze") # make the bank bank
exists = os.path.isfile('transaction_log.csv') # check if file exists
if exists == True:
load = raw_input("Welcome Back! Do you want to load previously saved data?:(y,n) ")
if load == "y":
reader = csv.reader(open("transaction_log.csv"))
for row in reader:
new_account = Account(row[1], row[2], int(row[3]), int(row[4]), int(row[5]), int(row[6]), int(row[7]), int(row[8]), row[9])
my_bank._accounts.update({row[0]: new_account})
print("Data Loaded.")
raw_input("**Press Enter to continue...")
x = 0
while x == 0:
os.system('cls' if os.name == 'nt' else 'clear')
print("----------------------------\nWelcome to the {}!\nPlease select an option: "
"\n1) SAVE & QUIT\n2) Grand Total in Bank\n3) Largest Account\n4) Make New Account(s)"
"\n5) Edit Account(s)\n----------------------------".format(my_bank._name))
option = raw_input("-> ")
if option == '1':
os.system('cls' if os.name == 'nt' else 'clear')
my_bank.save()
os._exit(0)
elif option == '2':
print("Total: ${0:.2f}".format(my_bank.grand_total)) # all_accounts.balance)
raw_input("\n**Press Enter to continue...")
os.system('cls' if os.name == 'nt' else 'clear')
x = 0
elif option == '3':
if len(my_bank._accounts.items()) == 0:
print("Create an account first.")
raw_input("\n**Press Enter to continue...")
else:
print("The largest account at this bank is {}.".format(my_bank.largest)) # all_accounts.balance)
raw_input("\n**Press Enter to continue...")
os.system('cls' if os.name == 'nt' else 'clear')
x = 0
elif option == '4':
os.system('cls' if os.name == 'nt' else 'clear')
do_next = 'y'
while do_next == 'y':
print("----------------------------\nLets create new accounts!\n")
owner = raw_input("Account owner -> ")
name = raw_input("Account nick-name -> ")
p = int(input("Number of pennies to deposit -> "))
n = int(input("Number of nickles to deposit -> "))
di = int(input("Number of dimes to deposit -> "))
q = int(input("Number of quarters to deposit -> "))
h = int(input("Number of half-dollars to deposit -> "))
do = int(input("Number of dollars to deposit -> "))
bugout = raw_input("Would you like this account to be a bug-out bag?(y,n): ")
new_account = Account(owner, name, p, n, di, q, h, do, bugout)
my_bank._accounts.update({name: new_account})
do_next = raw_input("Create another account?(y,n): ")
os.system('cls' if os.name == 'nt' else 'clear')
print("All account(s): ")
for k in my_bank._accounts.items():
print('Nick-Name: {0}\tOwner: {1}\tBugout?: {2:>5}'.format(k[0], k[1].owner, k[1].bug))
print"----------------------------"
raw_input("\n**Press Enter to continue...")
elif option == '5':
x = 1
while x == 1:
if len(my_bank._accounts.items()) == 0:
print("Create an account first.")
raw_input("\n**Press Enter to continue...")
x = 0
else:
print("All account(s): ")
for k in my_bank._accounts.items():
print('Nick-Name: {0}\tOwner: {1}\tBugout?: {2}'.format(k[0], k[1].owner, k[1].bug))
edit = raw_input("\nEnter nick-name of account to edit: ")
x = 2
while x == 2:
os.system('cls' if os.name == 'nt' else 'clear')
print("Account nick-name: {}\nWhat do you want to do?\n----------------------------\n1) Back...\n2) Withdraw"
"\n3) Deposit\n4) Transfer\n5) Get Balance\n6) Exchange Rates\n-----------------------------".format(edit))
option = raw_input("(1-5) -> ")
if option == '6':
bcx = my_bank._accounts[edit].balance / 303.76
euro = my_bank._accounts[edit].balance * 0.90
yen = my_bank._accounts[edit].balance * 120.57
print(u"Balance in Bitcoin: {0:.4f} \u0243".format(bcx))
print("Balance in Euro: {0:.2f} \xe2\x82\xac".format(euro))
print(u"Balance in Yen: {0:.2f} \u00A5".format(yen))
raw_input("\n**Press Enter to continue...")
elif option == '5':
print("Balance: ${0:.2f}".format(my_bank._accounts[edit].balance))
raw_input("\n**Press Enter to continue...")
elif option == '4':
if len(my_bank._accounts.items()) <= 1:
print("Create a second account first.")
raw_input("\n**Press Enter to continue...")
else:
acct_to = raw_input("Enter recieving account nick-name: ")
if my_bank._accounts[edit].owner != my_bank._accounts[acct_to].owner:
print "Error, cant not transfer coins from an account to an account owned by a different person."
else:
print("-----------------------------\nCurrent Account Balance: ${0:.2f}".format(my_bank._accounts[edit].balance))
print("Recipient Account Balance: ${0:.2f}\n-----------------------------".format(my_bank._accounts[acct_to].balance))
p = int(input("Number of pennies to transfer -> "))
n = int(input("Number of nickles to transfer -> "))
di = int(input("Number of dimes to transfer -> "))
q = int(input("Number of quarters to transfer -> "))
h = int(input("Number of half-dollars to transfer -> "))
do = int(input("Number of dollars to transfer -> "))
my_bank._accounts[edit].withdraw(p, n, di, q, h, do)
if my_bank._accounts[edit].p < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few pennies to transfer")
elif my_bank._accounts[edit].n < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few nickles to transfer")
elif my_bank._accounts[edit].di < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few dimes to transfer")
elif my_bank._accounts[edit].q < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few quarters to transfer")
elif my_bank._accounts[edit].h < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few half-dollars to transfer")
elif my_bank._accounts[edit].do < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few dollars to transfer")
elif my_bank._accounts[edit].balance < 0:
print("OVERDRAWN! Action declared invalid and undone! You will now be fined a huge ridiculous fee!")
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Balance: ${0:.2f}".format(my_bank._accounts[edit].balance))
else:
my_bank._accounts[acct_to].deposit(p, n, di, q, h, do)
print("Transfer Compleate.")
print("New Balance: ${0:.2f}".format(my_bank._accounts[edit].balance))
raw_input("\n**Press Enter to continue...")
elif option == '3':
p = int(input("Number of pennies to deposit -> "))
n = int(input("Number of nickles to deposit -> "))
di = int(input("Number of dimes to deposit -> "))
q = int(input("Number of quarters to deposit -> "))
h = int(input("Number of half-dollars to deposit -> "))
do = int(input("Number of dollars to deposit -> "))
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("New Balance: ${0:.2f}".format(my_bank._accounts[edit].balance))
raw_input("\n**Press Enter to continue...")
elif option == '2':
print("Balance: ${0:.2f}\n-----------------------------".format(my_bank._accounts[edit].balance))
p = int(input("Number of pennies to withdraw -> "))
n = int(input("Number of nickles to withdraw -> "))
di = int(input("Number of dimes to withdraw -> "))
q = int(input("Number of quarters to withdraw -> "))
h = int(input("Number of half-dollars to withdraw -> "))
do = int(input("Number of dollars to withdraw -> "))
my_bank._accounts[edit].withdraw(p, n, di, q, h, do)
if my_bank._accounts[edit].p < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few pennies to withdraw")
elif my_bank._accounts[edit].n < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few nickles to withdraw")
elif my_bank._accounts[edit].di < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few dimes to withdraw")
elif my_bank._accounts[edit].q < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few quarters to withdraw")
elif my_bank._accounts[edit].h < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few half-dollars to withdraw")
elif my_bank._accounts[edit].do < 0:
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Error: Too few dollars to withdraw")
elif my_bank._accounts[edit].balance < 0:
print("OVERDRAWN! Action declared invalid and automatically undone! You will now be fined a huge ridiculous fee!")
my_bank._accounts[edit].deposit(p, n, di, q, h, do)
print("Balance: ${0:.2f}".format(my_bank._accounts[edit].balance))
else:
print("New Balance: ${0:.2f}".format(my_bank._accounts[edit].balance))
raw_input("\n**Press Enter to continue...")
elif option == '1':
x = 0
else:
print("Error: Enter (1-5): ")
raw_input("\n**Press Enter to continue...")
else:
print("Error: Enter (1-5): ")
raw_input("\n**Press Enter to continue...")
if __name__ == '__main__':
main() |
c727f065a447dd92b4af53743e4300cc52c852a2 | bhelga/university | /python/Lab2/lab2_4.py | 2,322 | 3.8125 | 4 | from lab2 import correct_input
import math
def Queen(queeneX, queeneY, anotherX, anotherY):
R1 = queeneY - queeneX
R2 = queeneY + queeneX
if (anotherY == anotherX + R1 or anotherY == -anotherX + R2 or anotherY == queeneY or anotherX == queeneX):
return True
else:
return False
def King(kingX, kingY, anotherX, anotherY):
if (math.fabs(anotherX - kingX) <=1 and math.fabs(anotherY - kingY) <= 1):
return True
else:
return False
zahust = ""
stringx = "x:\t"
stringy = "y:\t"
print("Введiть координати фігур!\n\nБiлий ферзь:\n")
wqx = correct_input(1, 8, stringx)
wqy = correct_input(1, 8, stringy)
print("\nЧорний король:\n")
while True:
bkx = correct_input(1, 8, stringx)
bky = correct_input(1, 8, stringy)
if((bkx == wqx and bky == wqy)):
print("Error! This cell is full!\n")
else: break
print("\nЧорний ферзь:\n")
while True:
bqx = correct_input(1, 8, stringx)
bqy = correct_input(1, 8, stringy)
if((bqx == wqx and bqy == wqy) or (bqx == bkx and bqy == bky)):
print("Error! This cell is full!\n")
else: break
if Queen(bqx, bqy, bkx, bky):
zahust += "\nЧорний ферзь захищає короля"
if King(bkx, bky, bqx, bqy):
zahust += "\nЧорний король захищає ферзя"
if King(bkx, bky, wqx, wqy) and Queen(wqx, wqy, bqx, bqy):
print("Бiлий ферзь може побити чорного ферзя i короля та навпаки залежно вiд ходу." + zahust)
elif Queen(wqx, wqy, bqx, bqy) and not King(bkx, bky, wqx, wqy) and not Queen(wqx, wqy, bkx, bky):
print("Бiлий ферзь може побити чорного ферзя та навпаки залежно вiд ходу." + zahust)
elif Queen(wqx, wqy, bkx, bky) and Queen(wqx, wqy, bqx, bqy) and not King(bkx, bky, wqx, wqy):
print("Бiлий ферзь може побити чорного ферзя та навпаки залежно вiд ходу i чорного короля." + zahust)
elif King(bkx, bky, wqx, wqy) and not Queen(wqx, wqy, bqx, bqy):
print("Бiлий ферзь може побити чорного короля." + zahust)
else:
print("Нiхто нiкого не б'є" + zahust) |
e470fcae38620efaeb48979234997d43ff3a387c | ctac0h/jobeasy-algorithms-course | /Algorithms01/Home Work/Count Odd and Even.py | 383 | 4.15625 | 4 | def is_even(num):
if num % 2 == 0:
return True
return False
def count_even_odd(num):
evens = 0
odds = 0
for digit in str(num):
if is_even(int(digit)):
evens += 1
else:
odds += 1
return evens, odds
n = int(input("Enter a number: "))
result = count_even_odd(n)
print(f"Evens: {result[0]}\nOdds: {result[1]}") |
342a27dd5933453cc0c2ceeef95b0e99c174eef8 | Yoel101299/Python | /Ejercicio_29.py | 227 | 3.765625 | 4 | def esPar (num):
return num%2==0
i=0
suma_p=0
suma_i=0
while i<=10:
numero=int(input("Ingresa un numero "))
if esPar(numero):
suma_p=suma_p+numero
else:
suma_i=suma_i+numero
i=i+1
print(suma_p)
print(suma_i)
|
450d1571c4696a808fac60a7aec6eadacec52ce8 | estebansolo/PythonScripts | /scripts/matrices.py | 2,960 | 3.984375 | 4 | def print_matriz(matriz):
print(*matriz, sep="\n")
def matriz_bordes(length):
# Se utiliza el tamaño de la matriz para saber el final de la misma
matriz = []
for key_fila in range(length):
if key_fila == 0 or key_fila == (length - 1):
# Si es la primer o ultima fila, poner cada valor en 0
fila = ["0"] * length
else:
# Si no es ni la primera ni la ultima fila, solo poner
# la columna 0 y la ultima
fila = ["_"] * length
fila[0] = "0"
fila[length - 1] = "0"
matriz.append(fila)
print_matriz(matriz)
def diagonal_principal(length):
matriz = []
# Contador para saber que numero sigue en la secuencia
contador = 1
for key_fila in range(length):
fila = ["_"] * length
for key_columna in range(length):
if key_fila == key_columna:
# Si ambas posiciones son las mismas es donde va la diagonal
fila[key_columna] = str(contador)
# Se suma para tener el siguiente valor
contador += 1
# Agregar fila de valores
matriz.append(fila)
print_matriz(matriz)
def matriz_llena(length):
matriz = []
for key_fila in range(length):
fila = ["_"] * length
for key_columna in range(length):
# El valor es la suma de las indices de la matriz
fila[key_columna] = key_fila + key_columna
matriz.append(fila)
print_matriz(matriz)
def diagonales(length):
matriz = []
for key_fila in range(length):
fila = ["_"] * length
for key_columna in range(length):
if key_fila == key_columna:
# Si ambas posiciones son las mismas es donde va la diagonal
fila[key_columna] = "0"
# Segunda Diagonal
fila[length - 1 - key_fila] = "0"
matriz.append(fila)
print_matriz(matriz)
def main():
divisor = "*" * 50
print(divisor, "Matrices".center(50), divisor, sep="\n")
constante_matriz = int(input("Ingrese el tamaño de la matriz [>=3]: "))
if constante_matriz < 3:
constante_matriz = 3
while True:
menu = (
"A. Diagonales en 0",
"B. Bordes en 0",
"C. Matriz Llena",
"D. Diagonal Principal",
divisor
)
print(*menu, sep="\n")
opcion = input("Seleccione el tipo de matriz: ")
if opcion.lower() not in ["a", "b", "c", "d"]:
continue
if opcion.lower() == "a":
diagonales(constante_matriz)
elif opcion.lower() == "b":
matriz_bordes(constante_matriz)
elif opcion.lower() == "c":
matriz_llena(constante_matriz)
elif opcion.lower() == "d":
diagonal_principal(constante_matriz)
break
if __name__ == "__main__":
main() |
f567526cf58d2bacfeae74b3d6caeb8f2b6ed42a | pablodarius/mod02_pyhton_course | /Python Exercises/2_question16.py | 517 | 3.890625 | 4 | import unittest
# Display the cube of the number up to a given integer
def digits_cube(number):
for n in range(1, number + 1):
print("Current Number is : {} and the cube is {}".format(n, n**3))
class testing(unittest.TestCase):
def setUp(self):
print("Preparing context...")
self.number = 6
def test01(self):
digits_cube(self.number)
def tearDown(self):
print("Deleting context...")
del self.number
if __name__ == "__main__":
unittest.main()
|
857e667e6edf1acfc6cecf7b86aeb482cf74027c | ryndovaira/leveluppythonlevel1_300321 | /topic_05_data_structure/hw/generator_2_dict_pow2_start_stop_step_if_div3.py | 836 | 3.703125 | 4 | """
Функция dict_pow2_start_stop_step_if_div3.
Принимает 3 аргумента: числа start, stop, step.
Возвращает генератор-выражение состоящий из кортежа (аналог dict):
(значение, значение в квадрате)
при этом значения перебираются от start до stop (не включая) с шагом step
только для чисел, которые делятся на 3 без остатка.
Пример: start=0, stop=10, step=1 результат ((0, 0), (3, 9), (6, 36), (9, 81)).
Если start или stop или step не являются int, то вернуть строку 'Start and Stop and Step must be int!'.
Если step равен 0, то вернуть строку "Step can't be zero!"
""" |
4a73717d9c4df8ae01afe8170d05590594756e7a | nkozlova/concepts-of-programming-languages | /hw1/vm.py | 2,421 | 3.5 | 4 | import sys
import numpy as np
import instruction as ins
import memory as m
class VirtualMachine:
def __init__(self, memory):
self.memory = memory
self.offset = self.memory.get(0) # ячейки под регистеры
self.off = self.memory.get(len(ins.REGISTERS)) + self.offset - 1 # смещение под выводимый текст
def run(self):
while True:
command = self.memory.get(self.offset)
arg1 = self.memory.get(self.offset + 1)
arg2 = self.memory.get(self.offset + 2)
if not self.descriptor(command, arg1, arg2):
break
self.offset += 3
def descriptor(self, command, arg1, arg2):
if command == ins.STR_EXIT:
return False
if command == ins.STR_GET:
self.memory.set(arg1, input())
return True
if command == ins.STR_ADD:
self.memory.set(arg1, self.memory.get(arg1) + self.memory.get(arg2))
return True
if command == ins.STR_DEL:
self.memory.set(arg1, self.memory.get(arg1) / self.memory.get(arg2))
return True
if command == ins.STR_DEC:
if self.memory.get(arg1):
self.memory.set(arg1, self.memory.get(arg1) - 1)
return True
if command == ins.STR_INIT:
self.memory.set(arg1, arg2)
return True
if command == ins.STR_PR:
print(self.memory.get(arg1))
return True
if command == ins.STR_GOTO:
if self.memory.get(arg1):
self.offset = self.memory.get(0) + (arg2 - 1) * 3;
return True
if command == ins.STR_SAVE:
self.memory.set(arg1, self.memory.get(arg2))
return True
if command == ins.STR_PUTSTR:
string = ''
for i in range(int(arg2)):
string += chr(int(self.memory.get(self.off + arg1 + i)))
print(string)
return True
print("Wrong command ")
return False
if len(sys.argv) != 2:
print("Wrong input")
else:
mem = m.MemoryVM(500)
mem.set(0, len(ins.REGISTERS) + 1)
mem.set(1, 500)
file = np.fromfile(sys.argv[1], dtype=np.float32)
for i, s in enumerate(file):
mem.set(i + len(ins.REGISTERS), s)
vm = VirtualMachine(mem)
vm.run()
|
9f9acce322ca773b821af8af7b7851d303ef3167 | Andreas95H/Astronomical-Distance-Bootstrap | /pleiades.py | 1,289 | 3.78125 | 4 | """ Program to find distance to pleiades cluster using the bootstrap method"""
import random
import numpy as np
import matplotlib.pyplot as plt
def dist_calc():
'''Function that takes the distance modulus and its respective error for
each of the 18 stars used to determine the distance to the pleiades'''
mod = [5.77676, 5.61928, 5.5692, 5.5195, 5.67944, 5.54604, 5.582, 5.5748,
4.97352, 5.8086, 5.3978, 5.22568, 5.73708, 5.83736, 5.02264, 5.3772,
5.77752, 5.856] # distance modulus of each star
distance = [] #list for the calculated distance for each average magnitude
for i in range(10000):
sum_m = []
for n in range(18): # generates a sample of 18 stars
star = random.randint(0, 17) # randomly choosing a star
sum_m.append(mod[star])
m_mod = np.mean(sum_m)
dist = (10**(m_mod/5))*10 # calculated distance
distance.append(dist)
dist_f = np.mean(distance) # mean distance determined from the distribution
error_f = np.std(distance, ddof=1) # error from distribution's standard deviation
plt.hist(distance, bins=25)
plt.xlabel('Distance (kpc)')
plt.ylabel('No. of trials')
plt.savefig('pleiades.pdf')
return dist_f, error_f
|
a157235a5676f7035544e2bc7dec14a4ce211a24 | maneereddy/python-bootcamp | /day23%20question3.py | 1,130 | 3.578125 | 4 | #Import the required Libraries
import PyPDF2
from tkinter import *
from tkinter import filedialog
#Create an instance of tkinter frame
win= Tk()
#Set the Geometry
win.geometry("750x450")
#Create a Text Box
text= Text(win,width= 80,height=30)
text.pack(pady=20)
#Define a function to clear the text
def clear_text():
text.delete(1.0, END)
#Define a function to open the pdf file
def open_pdf():
file= filedialog.askopenfilename(title="Select a PDF", filetype=(("PDF Files","*.pdf"),("All Files","*.*")))
if file:
#Open the PDF File
pdf_file= PyPDF2.PdfFileReader(file)
#Select a Page to read
page= pdf_file.getPage(0)
#Get the content of the Page
content=page.extractText()
#Add the content to TextBox
text.insert(1.0,content)
def quit_app():
win.destroy()
my_menu= Menu(win)
win.config(menu=my_menu)
file_menu=Menu(my_menu,tearoff=False)
my_menu.add_cascade(label="File",menu= file_menu)
file_menu.add_command(label="Open",command=open_pdf)
file_menu.add_command(label="Clear",command=clear_text)
file_menu.add_command(label="Quit",command=quit_app)
win.mainloop() |
edefb02df17b05a1c173544c43c0b849d2b3190a | berquist/eg | /cpp/armadillo/schur_matrix_vector.py | 287 | 3.671875 | 4 | #!/usr/bin/env python
import numpy as np
dim = 3
A = np.ones(shape=(dim, dim))
B = A.copy()
b = np.empty(dim)
for i in range(dim):
b[i] = i + 2
print("A")
print(A)
print("b")
print(b)
for j in range(dim):
A[:, j] *= b[j]
print("% (1)")
print(A)
print("% (2)")
print(B * b)
|
4f247af14e0d6b96c642201340b38414ad366925 | Jane-Goza/Data-Visualization-With-Python | /data/piechart_medals.py | 449 | 3.84375 | 4 | import matplotlib.pyplot as plt
years = [1994, 1998, 2002, 2006, 2010, 2014]
pops = [4, 6, 40, 41, 25, 68]
# plot our chart with data above
plt.plot(years, pops, color=(0/255, 100/255, 100/255), linewidth=3.0)
#label on the left hand side
plt.ylabel("Population of sportmans in Russia")
#label on the bottom of the chart
plt.xlabel("Sportsmens Growth by Year")
#add a title to the chart
plt.title("World Population Growth", pad="20")
plt.show() |
02a206c74e70f1c81fedc896104c574c81dfd5d5 | alexandraback/datacollection | /solutions_5756407898963968_0/Python/Bfahy/magic.py | 1,240 | 3.703125 | 4 | #!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(description="google code jam magician")
parser.add_argument("inputfile", type=str, help="input file")
args = parser.parse_args()
outfile = open(args.inputfile + ".out", "w")
def read_input():
f = open(args.inputfile)
T = int(f.readline())
for i in range(T):
guess1 = int(f.readline())
grid1 = {}
for i in range(1,5):
grid1[i] = f.readline().split()
guess2 = int(f.readline())
grid2 = {}
for i in range(1,5):
grid2[i] = f.readline().split()
yield guess1, grid1, guess2, grid2
def output(n, s):
outstring = "Case #{}: {}\n".format(n, s)
print(outstring, end="")
outfile.write(outstring)
def main():
for n, case in enumerate(read_input(), start=1):
guess1, grid1, guess2, grid2 = case
row1 = grid1[guess1]
row2 = grid2[guess2]
match = [i for i in row1 if i in row2]
if len(match) == 1:
answer = match[0]
if len(match) > 1:
answer = "Bad magician!"
if len(match) < 1:
answer = "Volunteer cheated!"
output(n, answer)
if __name__ == "__main__":
main()
|
0e335a1711be821f81439d34ffb83a1709c30642 | bterwijn/python | /class_person_functions.py | 832 | 3.96875 | 4 |
def main():
person1 = Person("James", "Taylor", 70.5, 1.71) # object of class Person (variable of type Person)
person2 = Person("Jack", "Smith", 67.0, 1.65) # object of class Person
print(get_full_name(person1)) # James Taylor
print(get_full_name(person2)) # Jack Smith
print("BMI:", get_body_mass_index(person1)) # BMI: 23.938989774631512
print("BMI:", get_body_mass_index(person2)) # BMI: 24.609733700642796
class Person:
def __init__(self, first_name, last_name, weight, height):
self.name = first_name
self.surname = last_name
self.weight = weight
self.height = height
def get_full_name(person):
return person.name + ' ' + person.surname
def get_body_mass_index(person):
return person.weight / person.height**2
main()
|
ab7adae5f990f84bbbaeefc3573057c514ef83c8 | dorond/freecodecamp-basic-algorithm-challenges | /Check for Palindrones/palindrone-tests.py | 2,992 | 3.53125 | 4 | import unittest
import palindrone
class TestPalindrone(unittest.TestCase):
def test_palindrone_returns_boolean(self):
result = palindrone.checkPalindrone("eye")
self.assertIsInstance(result, bool, "Expected a bool in return, got a: " + str(type(result)))
def test_palindrone_eye_returns_true(self):
result = palindrone.checkPalindrone("eye")
self.assertTrue(result, "Expected True but got False")
def test_palindrone_check_leading_dash_returns_true(self):
result = palindrone.checkPalindrone("_eye")
self.assertTrue(result, "Expected True but got False")
def test_palindrone_check_spaces_returns_true(self):
result = palindrone.checkPalindrone("race car")
self.assertTrue(result, "Expected True but got False")
def test_palindrone_non_palindrone_should_return_false(self):
result = palindrone.checkPalindrone("not a palindrome")
self.assertFalse(result, "Expected False but got True")
def test_palindrone_check_long_sentence_with_punctuation_should_return_true(self):
result = palindrone.checkPalindrone("A man, a plan, a canal. Panama")
self.assertTrue(result, "Expected True but got False")
def test_palindrone_check_long_sentence_with_spaces_should_return_true(self):
result = palindrone.checkPalindrone("never odd or even")
self.assertTrue(result, "Expected True but got False")
def test_palindrone_single_word_non_palindrone_should_return_false(self):
result = palindrone.checkPalindrone("nope")
self.assertFalse(result, "Expected False but got True")
def test_palindrone_single_word_almost_palindrone_should_return_false(self):
result = palindrone.checkPalindrone("almostomla")
self.assertFalse(result, "Expected False but got True")
def test_palindrone_check_mix_punctuation_numbers_letters_spaces_should_return_true(self):
result = palindrone.checkPalindrone("My age is 0, 0 si ega ym.")
self.assertTrue(result, "Expected True but got False")
def test_palindrone_mixing_words_and_numbers_should_return_false(self):
result = palindrone.checkPalindrone("1 eye for of 1 eye.")
self.assertFalse(result, "Expected False but got True")
def test_palindrone_check_lots_of_synbols_and_numbers_should_return_true(self):
result = palindrone.checkPalindrone("0_0 (: /-\ :) 0-0")
self.assertTrue(result, "Expected True but got False")
def test_palindrone_mixing_words_and_symbols_should_return_false(self):
result = palindrone.checkPalindrone("five|\_/|four")
self.assertFalse(result, "Expected False but got True")
if __name__ == '__main__':
# Run the tests and print verbose output to stderr.
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestPalindrone))
unittest.TextTestRunner(verbosity=2).run(suite) |
763d2ce62c00049988d73e8ad3e9ca276d22eede | Kollaider/CheckiO | /checkio/elementary/between_markers.py | 1,041 | 4.40625 | 4 | """Between Markers.
URL: https://py.checkio.org/en/mission/between-markers-simplified/
DESCRIPTION:
You are given a string and two markers (the initial one and final).
You have to find a substring enclosed between these two markers.
But there are a few important conditions.
The initial and final markers are always different.
The initial and final markers are always 1 char size.
The initial and final markers always exist in a string and go one
after another.
INPUT/OUTPUT EXAMPLE:
between_markers('What is >apple<', '>', '<') == "apple"
between_markers('What is [apple]', '[', ']') == "apple"
between_markers('What is ><', '>', '<') == ""
between_markers('>apple<', '>', '<') == "apple"
"""
def between_markers(text: str, begin: str, end: str) -> str:
return text[text.find(begin) + 1:text.rfind(end)]
def main():
print(
f"between_markers('What is >apple<', '>', '<') == "
f"{between_markers('What is >apple<', '>', '<')}")
if __name__ == '__main__':
main()
|
f1c5aed43358c8617b29b729f8ae2dbe2e9dc26e | Joself/calendar | /calendarFunctions.py | 6,405 | 3.578125 | 4 | #!/usr/bin/env python3
import sys, pendulum, sqlite3
conn = sqlite3.connect('calendarData')
c = conn.cursor()
class bcolors:
HEADER = '\033[95m'
NEW = '\033[96m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
date = pendulum.now()
year = str(date.year)
if date.month < 10:
month = '0' + str(date.month)
else:
month = str(date.month)
if date.day < 10:
day = '0' + str(date.day)
else:
day = str(date.day)
now = 'd' + year + month + day
calendar = {}
def sanitiseTime(time, kind):
if ':' in time:
time = time.split(':')
time = int(time[0]) * 60 + int(time[1])
while True:
try:
time = int(time)
break
except ValueError:
print(f"Error in {kind} value:")
time = input(f"{time} is not an integer. Please enter an integer:\n")
while time % 5 != 0 or time > 1440:
if time % 5 != 0:
print(f"Error in {kind} value:")
print(f"Times are given in chunks of five minutes. {str(time)} is not a valid time.\n")
ans = input(f"r: Re-enter time.\nu: Round up to {str(5 * (time // 5 + 1))} minutes.\nd: Round down to {str(5 * (time // 5))} minutes.\n\n")
if ans == 'r':
while True:
try:
time = int(input('New time:\n'))
break
except ValueError:
print('\nPlease enter an integer:')
elif ans == 'u':
time = 5 * (time // 5 + 1)
elif ans == 'd':
time = 5 * (time // 5)
else:
print('Error: Invalid input. Must be \'r\', \'u\', or \'d\'. Starting over.')
if time > 1440:
print(f"Error in {kind} value:")
print(f"Times cannot exceed 1440. {str(time)} is not a valid time.\n")
ans = input('r: Re-enter time.\nd: Round down to 1440 minutes.\n')
if ans == 'r':
while True:
try:
time = int(input('New time:\n'))
break
except ValueError:
print('\nPlease enter an integer:')
elif ans == 'd':
time = 1440
else:
print('Error: Invalid input. Must be \'r\', or \'d\'. Starting over.')
return(time)
class newEvent:
def __init__(self, title, start, duration):
if start == 'a':
if calendar[now] == []:
start = 0
else:
lastEnd = 0
for i in calendar[now]:
if i.start > lastEnd:
start = lastEnd
break
elif i == calendar[now][-1]:
start = i.start + i.duration
break
else:
lastEnd = i.start + i.duration
else:
start = sanitiseTime(start, 'Start')
duration = sanitiseTime(duration, 'Duration')
self.title = title
self.start = start
self.duration = duration
if calendar[now] != []:
for i in range(len(calendar[now]) - 1, -1, -1):
if self.start > calendar[now][i].start:
calendar[now].insert(i + 1, self)
break
elif i == 0:
calendar[now].insert(0, self)
else:
calendar[now].append(self)
lastEnd = 0
for i in calendar[now]:
if i.start < lastEnd:
print(f"An event ends at {str(lastEnd)}, but the following event starts at {str(i.start)}. Adjusting.")
i.start = lastEnd
lastEnd = i.start + i.duration
def loadToday():
calendar[now] = []
c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=(?)", (now,))
if c.fetchone() != None:
for row in c.execute("SELECT * FROM " + now + " ORDER BY start"):
newEvent(row[2], str(row[0]), str(row[1]))
loadToday()
def updateToday():
c.execute("DROP TABLE IF EXISTS " + now)
c.execute("CREATE TABLE " + now + " (start integer, duration integer, title text)")
for i in calendar[now]:
c.execute("INSERT INTO " + now + " VALUES (?, ?, ?)", (i.start, i.duration, i.title,))
conn.commit()
def getTimes(i):
startH = str(i.start // 60)
startM = str(i.start % 60)
endH = str((i.start + i.duration) // 60)
endM = str((i.start + i.duration) % 60)
if len(startH) == 1:
startH = '0' + startH
if len(startM) == 1:
startM = '0' + startM
if len(endH) == 1:
endH = '0' + endH
if len(endM) == 1:
endM = '0' + endM
return(startH + ':' + startM + ' - ' + endH + ':' + endM + ' ' + i.title)
while True:
print(f"\n{bcolors.OKBLUE}{now[7:9]}/{now[5:7]}{bcolors.ENDC}")
ans = input(f"{bcolors.OKGREEN}a{bcolors.ENDC}: Add item\n{bcolors.HEADER}c{bcolors.ENDC}: Change item\n{bcolors.NEW}r{bcolors.ENDC}: Remove item\n{bcolors.OKBLUE}l{bcolors.ENDC}: List items\n{bcolors.WARNING}s{bcolors.ENDC}: Switch date\n{bcolors.FAIL}q{bcolors.ENDC}: Quit\n\n")
print()
if ans == 'q':
break
elif ans == 'l':
print(f"\n{bcolors.OKBLUE}{now[7:9]}/{now[5:7]}{bcolors.ENDC}")
for i in calendar[now]:
print(getTimes(i))
elif ans == 'a':
title = input('Title:\n')
start = input('Starting time (a for next available):\n')
duration = input('Duration:\n')
newEvent(title, start, duration)
updateToday()
elif ans == 's':
while True:
ans = input('Please input a date (d/m):\n')
if '/' not in ans:
print(f"Incorrect format. Correct format is d/m. Today\'s date with the correct format is {bcolors.OKBLUE}{str(date.day)}/{str(date.month)}{bcolors.ENDC}")
continue
else:
ans = ans.split('/')
try:
pendulum.date(year=date.year, month=int(ans[1]), day=int(ans[0]))
except ValueError:
print('Please use a date that exists.')
continue
if int(ans[1]) < 10:
ans[1] = '0' + ans[1]
if int(ans[0]) < 10:
ans[0] = '0' + ans[0]
now = 'd' + year + ans[1] + ans[0]
loadToday()
break
elif ans == 'r':
while True:
print('Remove which item?')
for i in range(len(calendar[now])):
print(f"{bcolors.FAIL}{str(i + 1)}{bcolors.ENDC} {getTimes(calendar[now][i])}")
try:
ans = int(input()) - 1
except ValueError:
print('Invalid number')
continue
try:
del(calendar[now][ans])
updateToday()
except IndexError:
print('Invalid number')
continue
break
elif ans == 'c':
while True:
print('Change which item?')
for i in range(len(calendar[now])):
print(f"{bcolors.FAIL}{str(i + 1)}{bcolors.ENDC} {getTimes(calendar[now][i])}")
try:
ans = int(input()) - 1
ans2 = []
for i in ['title', 'start', 'duration']:
ans2.append(input(f"Change {i} to what? (Blank for no change):\n"))
if ans2[-1] == '':
ans2[-1] = str(calendar[now][ans].__dict__[i])
del(calendar[now][ans])
newEvent(ans2[0], ans2[1], ans2[2])
updateToday()
except (ValueError, IndexError) as e:
print('Invalid number')
continue
break
conn.commit()
conn.close() |
38c755013b25fdcc31b287390907aac472a1ba56 | volkir31/university | /lab5/5_task.py | 1,324 | 3.875 | 4 | def comment_line(line):
if not line:
return False
return line[0] == '#'
def comment_in_line(line: str):
code_line = []
for symb in range(len(line)):
if line[symb] == '\'' or line[symb] == '"':
code_line.append(symb)
if not code_line and '#' in line:
return True, line.find('#')
for i in range(len(line)):
if line[i] == '#':
for j in range(len(code_line) - 1):
if code_line[j] < i < code_line[j + 1]:
if j % 2 == 1:
return True, i
elif i < code_line[0] or i > code_line[len(code_line) - 1]:
return True, i
return False, -1
def removeComments(file):
with open(file, 'r') as f:
output_string = []
for line in f:
line = line.strip("\n")
if comment_line(line):
continue
comment = comment_in_line(line)
if comment[0]:
pos = comment[1]
new_line = line[:-(len(line) - pos)]
if len(new_line) >= 3:
output_string.append(new_line)
else:
output_string.append(line)
return '\n'.join(output_string)
if __name__ == '__main__':
print(removeComments('1.txt'))
|
2fbacb855db39c4830051b2afa39e159ac86f86f | pinedab/soc_programs | /week2/d1/pthw/ex2.py | 429 | 3.765625 | 4 | ###### Python the Hard Way #####
###### #1mwtt sprinkles #####
# Exercise 2
print("Comments are started with '#'")
# print("This won't show")
print('Code like this is one way') # commenting...
print("This will run")
# Study Drills
print("The symbol '#' is called an:\n octothorpe")
#print("This will not print")
print("Back to printing")
print("...\nCheckcing for mistakes...\n...")
#Reading backwards
print("None found :D")
|
46b1aaae296a90a9101fbc357d10c9fc1dad8ae7 | rafaelmauricioaraujo/machine_learning | /NumPy/data_separation_tests.py | 1,375 | 3.53125 | 4 | # import NumPy into Python
import numpy as np
from sklearn.metrics import r2_score
# Create a 1000 x 20 ndarray with random integers in the half-open interval [0, 5001).
X = np.random.randint(0, 5001, (1000, 20))
# print the shape of X
print(X.shape)
# Average of the values in each column of X
ave_cols = X.mean(axis=0)
# Standard Deviation of the values in each column of X
std_cols = X.std(axis=0)
# Print the shape of ave_cols
print(ave_cols.shape)
# Print the shape of std_cols
print(std_cols.shape)
# Mean normalize X
X_norm = (X - ave_cols)/std_cols
# Print the average of all the values of X_norm
print(X_norm.mean())
# Print the average of the minimum value in each column of X_norm
print(X_norm.min())
# Print the average of the maximum value in each column of X_norm
print(X_norm.max())
# We create a random permutation of integers 0 to 4
print(np.random.permutation(5))
print('A partir daqui são testes para resolução do row_indices')
primeiro = np.random.permutation(9).reshape(3, 3)
print(primeiro)
print(primeiro.dtype)
print(primeiro.shape[0])
print(type(primeiro.shape[0]))
# Create a rank 1 ndarray that contains a random permutation of the row indices of `X_norm`
#tamanho = primeiro.shape[0]
#print(np.random.permutation(primeiro.shape[0]))
row_indices = np.random.permutation(primeiro.shape[0])
print('row_indices: ')
print(row_indices)
|
f4241f6ad88bd1e97ff3c53aafd796c359ed857f | gi-web/Python | /selfstudy/s09-01.py | 949 | 3.625 | 4 | ##커피자판기 사용을 함수를 이용하용하여 표현
##함수 선언##
def coffee_machine(user):
print("*********커피주문*********")
button=int(input(user+"씨 어떤커리를 드릴까요?(1:아메리카노, 2:카페라떼 3:카푸치노 4:에스프레소)"))
print("#1.뜨거운물준비")
print("#2.종이컵 준비")
if button==1:
print("#3.아메리카노 커피를 만든다")
elif button==2:
print("#3 까페라떼 커피를 만든다")
elif button==3:
print("#3 카푸치노 커피를 만든다")
elif button==4:
print("#3 에스프레소 커피를 만든다.")
print("#4 물을 붓는다")
print("#5.스푼으로 젖는다.")
print(user+"씨~ 커피 여기 있습니다.")
print("-----------------------------")
##함수사용##
coffee_machine("로제")
coffee_machine("리사")
coffee_machine("지수")
coffee_machine("제니")
|
9f1ed5644794f67bfa9dbe0cb7390ff45d03df98 | akxl/adventofcode2018 | /day6/part1.py | 3,362 | 3.90625 | 4 | # Advent of Code 2018 Day 5 Part 1
# Author: Aaron Leong
# Aim: I need to find the specified point with the largest number of other points that are closest to it, so long as that number is not infinite.
# My hypothesis is that, for a given Manhatten Grid and specified points, points that lie on the bonundary will have an infinite number of other points in the Grid that are closest to it. My question is then, how to I determine this boundary? So that I can pin point the specified points on the boundary so that I can discount them?
# My guess is that for the general case, I should search for the combinatio of specified points that I can put on the boundary that will give me the largest area.
# Or if I am lazy, I can just precalculate the boundary by hand for this particular exercise, and discount the points on said boundary.
# maybe the way to find the boundary is to maximize area but minimize perimeter?
# how do you find the minimum area that contains all points?
# maybe i can try adding one point at a time to a list (or find all possible combinations in a list of lists), and calculating the area of each permutation of that list, and find max? Question is, what happens when you use the polygon area function below when things intersect?
# My guess is that order does not matter.
import sys
def gridDistance(vector1, vector2):
if (len(vector1) != len(vector2)):
raise ValueError("vector1 and vector2 must have the same dimension/length")
length = len(vector1)
distance = 0
for i in range(0, length):
distance += abs(vector1[i] - vector2[i])
return(distance)
def get2dCoordinatesFurtherstFromOrigin(listOfCoordinates):
maxDistance = -(sys.maxsize)
furtherstPoint = (None, None)
for coordinates in listOfCoordinates:
distance = gridDistance((0, 0), coordinates)
if distance > maxDistance:
maxDistance = distance
furtherstPoint = coordinates
return(furtherstPoint)
def draw2dMapOfSpecifiedPoints(listOfCoordinates):
pointFurthestFromOrigin = get2dCoordinatesFurtherstFromOrigin(listOfCoordinates)
for i in range(0, pointFurthestFromOrigin[0] + 2):
row = ""
for j in range(0, pointFurthestFromOrigin[1] + 1):
if (j, i) in listOfCoordinates:
row += "P"
else:
row += "."
print(row)
def areaOfPolygonIn2dEuclideanSpace(listOfCoordinates):
numberOfCoordinates = len(listOfCoordinates)
area = 0
j = numberOfCoordinates - 1
for i in range(numberOfCoordinates):
area += ((listOfCoordinates[j][1] + listOfCoordinates[i][1]) * (listOfCoordinates[j][0] - listOfCoordinates[i][0]))
j = i
return(abs(area)/2.0)
def readInputs(filename):
f = open(filename, "r")
lines = f.read().split("\n")
result = []
for line in lines:
numbers = list(map(int, line.split(",")))
result.append((numbers[0], numbers[1]))
return(result)
if __name__ == "__main__":
#################### Part 1 tests
print(gridDistance((0,0),(1,2)) == 3)
testListOfCoordinates = [
(1, 1),
(1, 6),
(8, 3),
(3, 4),
(5, 5),
(8, 9)
]
print(get2dCoordinatesFurtherstFromOrigin(testListOfCoordinates) == (8,9))
print(areaOfPolygonIn2dEuclideanSpace([(2,2), (4,10), (9,7), (11,2)]) == 45.5)
draw2dMapOfSpecifiedPoints(testListOfCoordinates)
#################### Part 2 actual
input = readInputs("input.txt")
draw2dMapOfSpecifiedPoints(input) # will need to print this to a csv or something to visualise |
fdbd72e7b19a7742d5aae775664adc4573604dd3 | ZakHu7/LeetCode | /200-299/Q234.py | 1,262 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head):
if not head:
return True
# O(n) time, O(1) space
# Find length of list
runner = head
length = 0
while runner:
length += 1
runner = runner.next
if length % 2 == 0:
skip = length // 2
else:
skip = length // 2 + 1
reverseHead = head
for i in range(skip):
reverseHead = reverseHead.next
reverseHead = self.reverse(reverseHead)
for i in range(length - skip):
if head.val != reverseHead.val:
return False
head = head.next
reverseHead = reverseHead.next
return True
def reverse(self, head):
prev = after = None
while head:
after = head.next
head.next = prev
prev = head
head = after
return prev
s = Solution()
a1 = ListNode(1)
a2 = ListNode(1)
a3 = ListNode(2)
a4 = ListNode(1)
a1.next = a2
a2.next = a3
a3.next = a4
print(s.isPalindrome(a1)) |
d64917e3fb341d5ce71b13ed82c6bdbf8fd19a71 | BillyCussen/CodingPractice | /Python/Data Structures & Algorithms Module - Python/Week11/LinearSearch/LinearSearch2.py | 653 | 3.890625 | 4 | """
LinearSearch2.py
Billy Cussen
16/12/2020
"""
def linearSearch2(myArray, key):
for i in range(len(myArray)):
if myArray[i] == key:
return True
return False
myArr = [1,2,3,4,5,6,7,8,9,10]
print("Does Array Contain 2: "+str(linearSearch2(myArr, 2)))
print("Does Array Contain 4: "+str(linearSearch2(myArr, 4)))
print("Does Array Contain 6: "+str(linearSearch2(myArr, 6)))
print("Does Array Contain 8: "+str(linearSearch2(myArr, 8)))
print("Does Array Contain 10: "+str(linearSearch2(myArr, 10)))
print("Does Array Contain 12: "+str(linearSearch2(myArr, 12)))
print("Does Array Contain 14: "+str(linearSearch2(myArr, 14)))
|
087f8d6274138c2a20a1f4dfb625df0fcd35eb59 | tabatagloria/curso_video_Python | /Mundo_1-Fundamento/desafio_20.py | 230 | 3.65625 | 4 | #sorteando nomes
import random
alunos = []
for x in range(4):
alunos.append(input('Digite o nome do {}º aluno: '.format(x+1)))
random.shuffle(alunos)
print(alunos)
print('A ordem de apresentação será: {}'.format(alunos)) |
ca8a2342c7ef8f8ca549f176d4ab2e0298fb7658 | AlejandroVergunov/game | /bulls_and_cows.py | 2,011 | 3.9375 | 4 | # -*- coding: utf-8 -*-
#Генератор четырех случайных цифр, значения не повторяются.
from random import randint
#unknown - множество сгенерировано автоматом
#unknown_list - список из 4-х значений сгенерированный автоматом
#list_user_input - список из 4-х значений из ввода пользователя
x_cow = 0
x_bull = 0
y_bull = 0
def random_number():
'''Формирование списка из 4-х элементов от 0 до 9'''
unknown = set(str(randint(0, 9)))
while len(unknown) != 4:
x = str(randint(0, 9))
unknown.add(x)
unknown_list = [i for i in unknown]
return(unknown_list)
def user_input_number():
'''Формирование списка из пользовательского ввода'''
user_input = str(input('Введите 4-х значное число-> '))
list_user_input = list(user_input)
return list_user_input
unknown_list = random_number() # - список из 4-х случайных цифр от 0 до 9
#print(unknown_list)
while y_bull != 4:
y_bull = 0
y_cow = 0
user_list = user_input_number()
for i in user_list:
x_bull = user_list.index(i)
for j in unknown_list:
x_cow = unknown_list.index(j)
if ((x_bull == x_cow) and (i == j)):
y_bull +=1
if ((x_bull != x_cow) and (i == j)):
y_cow +=1
if y_bull == 0:
bulls = 'быков'
elif y_bull == 1:
bulls = 'бык'
else:
bulls = 'быка'
if y_cow == 0:
cows = 'коров'
elif y_cow == 1:
cows = 'корова'
else:
cows = 'коровы'
print(y_bull, '', bulls, '', y_cow, '' , cows)
input()
|
0f9266a0e88a03296fd846a25cc8aef67ed48461 | bunmiaj/CodeAcademy | /Python/Challenges/Exam_Statistics/grades.py | 4,203 | 4.59375 | 5 | # Print those grades
# As a refresher, let's start off by writing a function to print out the list of grades, one element at a time.
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
print_grades(grades)
# The sum of scores
# Now that we have a function to print the grades, let's create another function to compute the sum of all of the test grades.
# This will be super-helpful when we need to compute the average score.
# I know what you're thinking, "let's just use the built-in sum() function!" The built-in function would work beautifully, but it would be too easy.
# Computing the sum manually involves computing a rolling sum. As you loop through the list, add the current grade to a variable that keeps track of the total, let's call that variable total.
def grades_sum(scores):
total = 0
for grade in scores:
total += grade
return total
print grades_sum(grades)
# Computing the Average
# The average test grade can be found by dividing the sum of the grades by the total number of grades.
# Luckily, we just created an awesome function, grades_sum() to compute the sum.
# Instructions
# Define a function grades_average(), below the grades_sum() function that does the following:
# Has one argument, grades, a list
# Calls grades_sum with grades
# Computes the average of the grades by dividing that sum by float(len(grades)).
# Returns the average.
# Call the newly created grades_average() function with the list of grades and print the result.
def grades_average(grades):
sums = grades_sum(grades)
return sums / float(len(grades))
print grades_average(grades)
# The Variance
# Let's see how the grades varied against the average. This is called computing the variance.
# A very large variance means that the students' grades were all over the place,
# while a small variance (relatively close to the average) means that the majority of students did fairly well.
# Instructions
# On line 18, define a new function called grades_variance() that accepts one argument, scores, a list.
# First, create a variable average and store the result of calling grades_average(scores).
# Next, create another variable variance and set it to zero. We will use this as a rolling sum.
# for each score in scores: Compute its squared difference: (average - score) ** 2 and add that to variance.
# Divide the total variance by the number of scores.
# Then, return that result.
# Finally, after your function code, print grades_variance(grades).
def grades_variance(scores):
average = grades_average(scores)
variance = 0
for score in scores:
var = (average - score) ** 2
variance += var
return variance / len(scores)
print grades_variance(grades)
# Standard Deviation
# Great job computing the variance! The last statistic will be much simpler: standard deviation.
# The standard deviation is the square root of the variance. You can calculate the square root by raising the number to the one-half power.
# Instructions
# Define a function grades_std_deviation(variance).
# return the result of variance ** 0.5
# After the function, create a new variable called variance and store the result of calling grades_variance(grades).
# Finally print the result of calling grades_std_deviation(variance).
def grades_std_deviation(variance):
return variance ** 0.5
variance = grades_variance(grades)
print grades_std_deviation(variance)
# Review
# You've done a great job completing this program.
# We've created quite a few meaningful functions. Namely, we've created helper functions to print a list of grades, compute the sum, average, variance, and standard deviation about a set of grades.
# Let's wrap up by printing out all of the statistics.
# Who needs to pay for grade calculation software when you can write your own? :)
# Instructions
# Print out the following:
# all of the grades
# sum of grades
# average grade
# variance
# standard deviation
print print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
print grades_std_deviation(variance) |
b1b29f974d32c58f64ff4414f18c48aa5f62e1c4 | busz/my_leetcode | /python/maximum_subarray.py | 908 | 3.875 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2014-3-18
leetcoder : maximum subarray
Problem : Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
@author: xqk
'''
class Solution:
# @param A, a list of integers
# @return an integer
def maxSubArray(self, A):
if len(A) == 1:
return A[0];
maxSum = A[0]
maxhere = A[0];
for i in range(len(A) - 1):
if maxhere < 0 :
maxhere = A[i+1];
else:
maxhere = maxhere + A[i+1]
if maxhere > maxSum:
maxSum = maxhere;
return maxSum
A = [-2, 1,-3,4,-1,2,1,-5,4]
test = Solution()
print test.maxSubArray(A) |
ec648d2c11a556527b9e59dec796c87e954ba507 | C-MTY-TC1028-031-2113/tarea1-basicos-A00833404 | /assignments/01Promedio/src/exercise.py | 413 | 3.640625 | 4 | def main():
#escribe tu código abajo de esta línea
mat1 = float(input("Calificación de la materia: "))
mat2 = float(input("Calificación de la materia: "))
mat3 = float(input("Calificación de la materia: "))
mat4 = float(input("Calificación de la materia: "))
prom = (mat1 + mat2 + mat3 + mat4)/4
print("El promedio es: " + str(prom))
main()
if __name__ == '__main__':
main() |
a17b134238eb31f9d5f7a78b24204cc1f5892ef9 | SviatoslavPereverziev/Course | /Задания /Задачи/Lesson9-10_1526065055/lesson10/dict_.py | 300 | 3.5625 | 4 | d = {i:i+2**i for i in range(10)}
a={i+2**i:i for i in range(10)}
c=[i for i in range(10,20)]
e = {key:value for key, value in zip(c,d.items())}
print(e)
for key in d:
print (key)
for value in d.values():
print (value)
for item in d.items():
print(item)
print(d.get(999))
|
f0ee45b177834d1c607309f3944aafa97d36f746 | zgy3zgy3/AID1912 | /thread2.py | 306 | 3.5 | 4 | from threading import Thread
from time import sleep
def fun (sec,name):
print("含有参数的线程")
sleep(2)
print("%s执行完毕"%name)
jobs =[]
for i in range(3):
t = Thread(target=fun,args=(2,),kwargs={"name":"%d"%i})
jobs.append(t)
t.start()
for i in jobs:
i.join()
|
433c3817d9ca3e17b1bb588272f34285b207f829 | mpieciak18/codewars_solutions | /6kyu/braking_well.py | 1,620 | 4.03125 | 4 | # Braking distance d1 is the distance a vehicle will go from the point when it
# brakes to when it comes to a complete stop. It depends on the original speed v
# and on the coefficient of friction mu between the tires and the road surface.
# The braking distance is one of two principal components of the total stopping
# distance. The other component is the reaction distance, which is the product
# of the speed and the perception-reaction time of the driver.
# The kinetic energy E is 0.5*m*v**2, the work W given by braking is mu*m*g*d1.
# Equalling E and W gives the braking distance: d1 = v*v / 2*mu*g where g is
# the gravity of Earth and m the vehicle's mass.
# We have v in km per hour, g as 9.81 m/s/s and in the following we suppose that
# the reaction time is constant and equal to 1 s. The coefficient mu is
# dimensionless.
# There are two tasks.
# The first one is to calculate the total stopping distance in meters given
# v, mu (and the reaction time t = 1).
# dist(v, mu) -> d = total stopping distance
# The second task is to calculate v in km per hour knowing d in meters and
# mu with the supposition that the reaction time is still t = 1.
# speed(d, mu) -> v such that dist(v, mu) = d.
#Examples:
# dist(100, 0.7) -> 83.9598760937531
# speed(83.9598760937531, 0.7) -> 100.0
def dist(v, mu):
v = v / 3.6
react_dist = v
brake_dist = (v**2) / (2 * mu * 9.81)
total_dist = react_dist + brake_dist
return total_dist
def speed(d, mu):
z = 1 / (2 * mu * 9.81)
v = (-1 + (1 - 4 * z * (-d))**0.5) / (2 * z)
v = v * 3.6
return v |
1357814c300346ae546a43d947ba36247c3d96ac | eaniyom/python-challenge-solutions | /Aniyom Ebenezer/phase 1/python 2 basis/Day_17_Challenge_Solution/Question 1 Soln.py | 320 | 3.71875 | 4 | """
Write a Python function that takes a sequence of numbers and determine whether all numbers are different from each other
"""
def test_distinct(data):
if len(data) == len(set(data)):
return True
else:
return False
print(test_distinct([1, 5, 7, 9]))
print(test_distinct([2, 7, 5, 8, 8, 9, 0])) |
a161b5146c6a75d0d39130924451f59b902f10df | technology-research/leetcode | /24.Swap-Nodes-in-Pairs.py | 1,642 | 3.96875 | 4 | """
24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
import unittest
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
next_header = head
if head and head.next:
next_header, head.next.next, head.next = head.next, head, self.swapPairs(head.next.next)
return next_header
class SwapNodesInPairsCase(unittest.TestCase):
def create_list(self, arr: List[int]):
if len(arr) == 0:
return None
pre_head = ListNode(None)
target = pre_head
for i in arr:
target.next = ListNode(i)
target = target.next
return pre_head.next
def print_nodes(self, head: ListNode):
res = []
target = head
while target:
res.append(target.val)
target = target.next
return ",".join([str(e) for e in res])
def test_swap_nodes_in_pairs(self):
s = Solution()
for i, o in [([1,2,3,4], [2,1,4,3])]:
self.assertEqual(self.print_nodes(s.swapPairs(self.create_list(i))), self.print_nodes(self.create_list(o)))
if __name__ == '__main__':
s = Solution()
unittest.main()
# s = SwapNodesInPairsCase()
# a = s.create_list([2,1,4,3])
# print(s.print_nodes(a))
|
aebd69e1398e2e444687c975eb05cd08bb4d4bea | GabrielAquila/Calculadora-Python | /Calculadora.py | 4,539 | 3.75 | 4 | # importando tkinter
from tkinter import *
from tkinter import ttk
#cores
cor1 = "#1c1c1b" #black/preto
cor2 = "#feffff" #white/branco
cor3 = "#0e2747" #blue/azul
cor4 = "#dbd9d7" #gray/cinza
cor5 = "#de7233" #orange/laranja
janela =Tk()
janela.title("Calculadora")
janela.geometry("235x310")
janela.config(bg=cor1)
#criação de frames
frame_tela = Frame(janela, width=235, height=50, bg=cor3)
frame_tela.grid(row=0, column=0)
frame_corpo = Frame(janela, width=235, height=268)
frame_corpo.grid(row=1, column=0)
#variavel todos valores
todos_valores = ''
#criação de label
valor_texto = StringVar()
#criação das função
def entrar_valores(event):
global todos_valores
todos_valores =todos_valores + str(event)
valor_texto.set(todos_valores)
#criação da função para calcular
def calcular():
global todos_valores
resultado = eval(todos_valores)
valor_texto.set(resultado)
#criação da função limpar tela
def limpar_tela():
global todos_valores
todos_valores =""
valor_texto.set("")
app_label = Label(frame_tela, textvariable=valor_texto, width=16, height=2, padx=7, relief=FLAT, anchor="e", justify=RIGHT, font=('ivy 18'), bg=cor3, fg=cor2)
app_label.place(x=0,y=0)
#criação de botoes
b_1 = Button(frame_corpo, command=limpar_tela, text="C", width=11, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_1.place(x=0, y=0)
b_2 = Button(frame_corpo, command = lambda: entrar_valores('%'), text="%", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_2.place(x=118, y=0)
b_3 = Button(frame_corpo, command = lambda: entrar_valores('/'), text="/", width=5, height=2, bg=cor5, fg=cor2, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_3.place(x=177, y=0)
b_4 = Button(frame_corpo, command = lambda: entrar_valores('7'), text="7", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_4.place(x=0, y=52)
b_5 = Button(frame_corpo, command = lambda: entrar_valores('8'), text="8", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_5.place(x=59, y=52)
b_6 = Button(frame_corpo, command = lambda: entrar_valores('9'), text="9", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_6.place(x=118, y=52)
b_7 = Button(frame_corpo, command = lambda: entrar_valores('*'), text="*", width=5, height=2, bg=cor5, fg=cor2, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_7.place(x=177, y=52)
b_8 = Button(frame_corpo, command = lambda: entrar_valores('4'), text="4", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_8.place(x=0, y=104)
b_9 = Button(frame_corpo, command = lambda: entrar_valores('5'), text="5", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_9.place(x=59, y=104)
b_10 = Button(frame_corpo, command = lambda: entrar_valores('6'), text="6", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_10.place(x=118, y=104)
b_11 = Button(frame_corpo, command = lambda: entrar_valores('-'), text="-", width=5, height=2, bg=cor5, fg=cor2, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_11.place(x=177, y=104)
b_12 = Button(frame_corpo, command = lambda: entrar_valores('1'), text="1", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_12.place(x=0, y=156)
b_13 = Button(frame_corpo, command = lambda: entrar_valores('2'), text="2", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_13.place(x=59, y=156)
b_14 = Button(frame_corpo, command = lambda: entrar_valores('3'), text="3", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_14.place(x=118, y=156)
b_15 = Button(frame_corpo, command = lambda: entrar_valores('+'), text="+", width=5, height=2, bg=cor5, fg=cor2, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_15.place(x=177, y=156)
b_16 = Button(frame_corpo, command = lambda: entrar_valores('0'), text="0", width=11, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_16.place(x=0, y=208)
b_17 = Button(frame_corpo, command = lambda: entrar_valores('.'), text=".", width=5, height=2, bg=cor4, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_17.place(x=118, y=208)
b_18 = Button(frame_corpo, command = calcular, text="=", width=5, height=2, bg=cor5, fg=cor2, font=('ivy 13 bold'), relief=RAISED, overrelief=RIDGE)
b_18.place(x=177, y=208)
janela.mainloop()
|
fe93f12bb90a727d7242f36b744d28bce12e590c | buy/leetcode | /python/35.search_insert_position.py | 912 | 4.0625 | 4 | # Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
# You may assume no duplicates in the array.
# Here are few examples.
# [1,3,5,6], 5 → 2
# [1,3,5,6], 2 → 1
# [1,3,5,6], 7 → 4
# [1,3,5,6], 0 → 0
class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer}
# 7:14
def searchInsert(self, nums, target):
if not nums or target is None:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) / 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
if nums[mid] > target:
return mid
else:
return mid + 1
|
20647d9ab1c43ec07ceab6ce2eef9e51ca7d15ea | marshallhumble/Coding_Challenges | /Code_Eval/Hard/StringSearching/StringSearching.py | 1,374 | 4.4375 | 4 | #!/usr/bin/env python
"""
String Searching
Challenge Description:
You are given two strings. Determine if the second string is a substring of the first (Do NOT use any substr type
library function). The second string may contain an asterisk(*) which should be treated as a regular expression i.e.
matches zero or more characters. The asterisk can be escaped by a \ char in which case it should be interpreted as a
regular '*' character. To summarize: the strings can contain alphabets, numbers, * and \ characters.
Input sample:
Your program should accept as its first argument a path to a filename. The input file contains two comma delimited
strings per line. E.g.
Hello,ell
This is good, is
CodeEval,C*Eval
Old,Young
Output sample:
If the second string is indeed a substring of the first, print out a 'true'(lowercase), else print out a
'false'(lowercase), one per line. E.g.
true
true
true
false
"""
import sys
def is_substring(a, b):
a = a.replace("*", "@")
b = b.replace("\\*", "@")
for e in b.split("*"):
pos = a.find(e)
if pos < 0:
return False
a = a[pos + len(e):]
return True
def main():
with open(sys.argv[1], "r") as f:
for line in f.readlines():
a, b = line.rstrip().split(",")
print(str(is_substring(a, b)).lower())
if __name__ == "__main__":
main()
|
6ee0437af62e84a554205a0cacfb060a48fc19d9 | elenaborisova/Python-Advanced | /08. Comprehension - Exercise/02_words_lengths.py | 107 | 3.8125 | 4 | words = input().split(", ")
result = [f"{word} -> {len(word)}" for word in words]
print(", ".join(result))
|
17739ef241342e819cacbd7f8422f2fb29e4b7bd | kprashant94/Codes | /Queue/queue_enqueue.py | 507 | 4.09375 | 4 |
#####################################################################
# Title: Queue
# Algorithm: enqueue
# Project: codewarm.in
#
# Description:
# In the this code the method 'enqueue' takes the 'queue' and the key
# (to be inserted in queue) as its aruguments and inserts it at the
# tail of the queue by appending the key in the list.
#
#####################################################################
class Queue:
def __init__(self):
self.Q = []
def enqueue(self, a):
self.Q.append(a) |
15a3580ae2a42e66f28f486f197fe12168cb22ee | arvindiyengar/PythonTraining | /demo12.py | 785 | 3.671875 | 4 | '''
DataStructures : Sets
'''
print("Script Starting...")
set1 = {"Earth", "Sun", "Mars", "Jupiter", "Saturn"}
set2 = {"Earth", "Uranus"}
# Change an element
print("Entire Set : ", set1)
# set1[1] = "New Planet" # Throws an error
# Adding a new value
print("\n\nAdding new value\n\n")
print("Old set :", set1)
set1.add("Venus")
print("Updated Set : ", set1)
# copy the set
print("\n\Copying new Set\n\n")
set3 = set1.copy()
print("Copied Set", set3)
# Union of 2 sets
print("\n\nUnion Operation\n\n")
print("Set1 : ", set1)
print("Set2 : ", set2)
print("Union Set : ", set1.union(set2))
# Union of 2 sets
print("\n\nIntersection Operation\n\n")
print("Set1 : ", set1)
print("Set2 : ", set2)
print("Union Set : ", set1.intersection(set2))
print("\n\nScript Executed")
|
3eb9f83b2276ad74aa2ef6ba7c41e3db5f3034fa | Bianca-22/Blue_T3C6-mod1 | /Projeto 03 - Jogo Dados.py | 2,072 | 3.71875 | 4 | # Importando bibliotecas e suas funções
from random import randint
from time import sleep
jogador = {}
num = int(input('Quantas rodadas você vai querer jogar? '))
# O For irá rodar conforme a quantidade de rodadas que o usuário escolher
for r in range(1,num+1):
print('\n***'*20)
print(f'{r}° RODADA')
# Esse For é para a quantidade de jogadores
for j in range(1,5):
print('\n-<-'*20)
print(f'{j}° JOGADOR')
dado = randint(1,6)
# Adicionando ao dicionário 'jogador' a chave (Jogador...) e o valor do dado
jogador[f'Jogador {j}'] = dado
print('ROLANDO OS DADOS')
sleep(1)
print(f'O dado caiu no número {dado}')
jogador.copy()
print('\n---'*20)
if jogador['jogador2'] < jogador['jogador1'] > jogador['jogador3'] and jogador['jogador1'] > jogador['jogador4']:
situacao = 'jogador1'
play1 += 1
elif jogador['jogador1'] < jogador['jogador2'] > jogador['jogador3'] and jogador['jogador2'] > jogador['jogador4']:
situacao = 'jogador2'
play2 += 1
elif jogador['jogador1'] < jogador['jogador3'] > jogador['jogador2'] and jogador['jogador3'] > jogador['jogador4']:
situacao = 'jogador3'
play3 += 1
elif jogador['jogador2'] < jogador['jogador4'] > jogador['jogador3'] and jogador['jogador4'] > jogador['jogador1']:
situacao = 'jogador4'
play4 += 1
else:
situacao = 'Empate'
print(f'O ganhador da rodada é o {situacao}\n')
if play2 < play1 > play3 and play1 > play4:
print(f' O campeão foi o Jogador 1 com {play1} Vitorias')
elif play1 < play2 > play3 and play2 > play4:
print(f' O campeão foi o Jogador 1 com {play2} Vitorias')
elif play1 < play3 > play2 and play3 > play4:
print(f' O campeão foi o Jogador 1 com {play3} Vitorias')
elif play2 < play4 > play3 and play4 > play1:
print(f' O campeão foi o Jogador 1 com {play4} Vitorias')
else:
print('O resultado terminou em empate.')
|
53a9439e69d70d6e82e560a8be9beb66052524ee | vini52/Exercicios_PI_Python | /ep3/ep3_5.py | 96 | 3.921875 | 4 | num = int(input())
soma = num
while num != 0:
num = int(input())
soma += num
print(soma) |
2d431b340a00dd7ac3f99dddec6bc97340725d8e | lingerssgood/AI | /DataTools/numpyDemo.py | 5,820 | 3.875 | 4 | import numpy as np
'''
ndim:维度
shape:行数和列数
size:元素个数
'''
import numpy as np
array=np.array([[1,2,3],[2,3,4]])
print(array.ndim)
print(array.shape)
print(array.size)
'''
array:创建数组
dtype:指定数据类型
zeros:创建数据全为0
ones:创建数据全为1
empty:创建数据接近0
arrange:按指定范围创建数据
linspace:创建线段
'''
#创建数组
a=np.array([[2,23,4],[2,3,4]])
print(a)
#指定数据 dtype
a=np.array([23,24,56],dtype=np.int)
print(a)
a=np.array([23,24,56],dtype=np.float)
print(a)
a=np.array([23,24,56],dtype=np.int32)
print(a)
a=np.array([23,24,56],dtype=np.float32)
print(a)
#创建数据全为0
a=np.zeros((3,4))
print(a)
#创建一维数组
a=np.ones((3,4),dtype=np.int)
print(a)
a=np.empty((3,4))
print(a)
#用arange创建连续数组,10-19,间隔是2
a=np.arange(10,20,2)
print(a)
#reshape,改变数据的形状
a=np.arange(12).reshape((3,4))
print(a)
#创建线段数据,开始1,结束10,且分割成20个,生成线段
a=np.linspace(1,10,20)
print(a)
a=np.linspace(1,10,20).reshape(5,4)
print(a)
'''
基础运算
'''
import numpy as np
a=np.array([10,20,30,40]) # array([10, 20, 30, 40])
b=np.arange(4) # array([0, 1, 2, 3])
#一维数据的计算
c=a+b
c=a*b
c=a-b
c=b**2
c=10*np.sin(a)#调用np中的数学函数
print(b<3)
'''
多行多维的运算
'''
#矩阵的乘法
a=np.array([[1,1],[0,1]])
b=np.arange(4).reshape((2,2))
c_dot=np.dot(a,b)
c_dot2=a.dot(b)
print(c_dot)
print(c_dot2)
import numpy as np
a=np.random.random((2,4))
#生成2行 4列的浮点数,浮点数都是从0-1中随机
print(a)
np.sum(a)
np.min(a)
np.max(a)
#axis=0,以列为主;axis=1,以行为主
print("a=",a)
print("sum=",np.sum(a,axis=1))
print("min=",np.sum(a,axis=0))
print("max=",np.sum(a,axis=1))
import numpy as np
a=np.arange(2,14).reshape(3,4)
print(a)
'''
random用法
'''
print(np.random.randint(1,10) ) # 产生 1 到 10 的一个整数型随机数
print(np.random.random() ) # 产生 0 到 1 之间的随机浮点数
print(np.random.uniform(1.1,5.4) ) # 产生 1.1 到 5.4 之间的随机浮点数,区间可以不是整数
print(np.random.choice(['Low','Medium','High'],20)) # 从序列中随机选取一个元素
print(np.random.randrange(1,100,2) ) # 生成从1到100的间隔为2的随机整数
print(np.random.sample([1, '23', [4, 5]], 2))#random.sample([], n),列表元素任意n个元素的组合,示例n=2
'''
loc:float
此概率分布的均值(对应着整个分布的中心centre)
scale:float
此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,
scale越小,越瘦高)
size:int or tuple of ints
输出的shape,默认为None,只输出一个值
'''
mu, sigma = 0, .1
s = np.random.normal(loc=mu, scale=sigma, size=1000)
a=[1,3,5,6,7] # 将序列a中的元素顺序打乱
np.random.shuffle(a)
print(a)
#argmin:最小元素索引;argmax:最大元素索引
print(np.argmin(a))
print(np.argmax(a))
#mean矩阵的均值
print(np.mean(a))
print(np.average(a))
print(a.mean())
#矩阵的中位数
# print(a.median())
#累加函数cumsum每累加一次,记一次值
print(np.cumsum(a))
#累差函数,计算每一行中后一项与前一项之差,3行4列得到3行3列矩阵
print(np.diff(a))
#返回数组a中非零元素的索引值数组。
#二维数组行返回,列也返回,零元素不返回
print(np.nonzero(a))
#排序
b=np.arange(14,2,-1).reshape((3,4))
print(b)
print(np.sort(b))
#矩阵转置
print(np.transpose(b))
print(b.T)
#clip(array,array_min,array_max)
#比最小值小的变成最小值,大的变成最大值
print(np.clip(b,5,9))
#一维索引
import numpy as np
c=np.arange(3,15)
print(c[3])
#一维转成二维
d=np.arange(3,15).reshape(3,4)
print(d)
print(d[2])#对应第三行
print(d[1][1])
print(d[1,1])
#切片
print(d[1,1:3])#从1开始不包括3
'''
逐行逐列打印
'''
for row in d:
print(row)
for column in d.T:
print(column)
'''
这一脚本中的flatten是一个展开性质的函数,将多维的矩阵进行展开成1行的数列。而flat是一个迭代器,本身是一个object属性。
'''
print(d.flatten())
for item in d.flat:
print(item)
#Numpy array 合并
#按行、列多种方式合并
import numpy as np
a=np.array([1,1,1])
b=np.array([2,2,2])
print(np.vstack((a,b)))
'''
vertical stack本身属于一种上下合并,即对括号中的两个整体进行对应操作。
此时我们对组合而成的矩阵进行属性探究
'''
c=np.vstack((a,b))
print(a.shape,c.shape)
'''
利用shape函数可以让我们很容易地知道A和C的属性,从打印出的结果来看,A仅仅是一个拥有3项元素的数组(数列),
而合并后得到的C是一个2行3列的矩阵。
介绍完了上下合并,我们来说说左右合并:
'''
d=np.hstack((a,b))
print(d)
print(a.shape,d.shape)
'''
说完了array的合并,我们稍稍提及一下前一节中转置操作,如果面对如同前文所述的A序列, 转置操作便很有可能无法对其进行转置(因为A并不是矩阵的属性),
此时就需要我们借助其他的函数操作进行转置:
'''
print(a[np.newaxis,:])
print(a[np.newaxis,:].shape)
print(a[:,np.newaxis])
print(a[:,np.newaxis].shape)
'''
结合着上面的知识,我们把它综合起来:
'''
import numpy as np
A = np.array([1, 1, 1])[:, np.newaxis]
B = np.array([2, 2, 2])[:, np.newaxis]
C = np.vstack((A, B)) # vertical stack
D = np.hstack((A, B)) # horizontal stack
print(D)
print(A.shape, D.shape)
'''
当你的合并操作需要针对多个矩阵或序列时,
借助concatenate函数可能会让你使用起来比前述的函数更加方便:
'''
c=np.concatenate((a,b,b,a),axis=0)#按行
print(c)
d=np.concatenate((a,b,b,a),axis=1)#按列
print(d) |
1698199ee35f29fa8a5bad0657a09940b898d3f7 | NicolasAskel/Avaliativo_1 | /exercicio20.py | 81 | 3.625 | 4 | numero = (float(input("insira massa em kg: ")))
print("em libras:",(numero)/0.45) |
4c1c78791216a463114c05d93a87999591c9f2bc | pdelfino/numerical-analysis | /lista-5/3-b-questao-delfino.py | 1,196 | 3.5625 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
import pylab
def analitic(x):
return (np.sqrt(1+(x**2))) - 1
"""
print (analitic(0.1))
print (analitic(0.5))
print (analitic(0.8))
"""
def euler(x):
y_init = 0
x_init = 0
old_dy_dx = x_init/(1+y_init)
old_y = y_init
new_y = None
new_dy_dx = None
h = 0.1
limite = 0
i = 0
x_new = x_init
while x>=limite:
i+=1
#print ("iterada", i)
new_y = (h*old_dy_dx) + old_y
#print ("new_y", new_y)
x_new += h
new_dy_dx = x_new/(1+new_y)
#print ("new dy_dx", new_dy_dx)
old_y = new_y
old_dy_dx = new_dy_dx
limite = limite + h
return new_y
print (euler(0.8),analitic(0.8))
t = np.linspace(0,1,5)
lista_outputs = []
for i in t:
lista_outputs.append(euler(i))
print (lista_outputs)
plt.plot(t, analitic(t), 'bs', label='Output resultado analítico')
plt.plot(t , lista_outputs, 'ro', label="Output resultado numérico")
plt.title('Comparação Euler/Analítico - tolerância: 0.1')
pylab.legend(loc='upper left')
plt.show()
|
7375c18e1831cc20dcb527aa0555b1c1cbea627c | TaeHongGil/study | /ysum.py | 664 | 3.5625 | 4 | def solution(n):
answer = 0
for i in range(1,n+1):
if(n%i==0):
answer+=i
#return sum([i for i in range(1,num+1) if num%i==0])
return answer
n=12
print(solution(n))
'''
문제 설명
정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요.
제한 사항
n은 0 이상 3000이하인 정수입니다.
입출력 예
n return
12 28
5 6
입출력 예 설명
입출력 예 #1
12의 약수는 1, 2, 3, 4, 6, 12입니다. 이를 모두 더하면 28입니다.
입출력 예 #2
5의 약수는 1, 5입니다. 이를 모두 더하면 6입니다.
'''
|
f48e590d6c413b87c60daee38cf8cdd60f69690d | eldadpuzach/MyPythonProjects | /Basics/decimals.py | 290 | 3.859375 | 4 | import decimal
# Output: 0.1
print(0.1)
# Output: Decimal('0.1000000000000000055511151231257827021181583404541015625')
print(decimal.Decimal(0.1))
from decimal import Decimal as D
# Output: Decimal('3.3')
print(D('1.1') + D('2.2'))
# Output: Decimal('3.000')
print(D('1.2') * D('2.50')) |
d987bbf3999fdd90654622a74a00b5ebaa849002 | NTHThinh/Code_Python | /Python_Basic/list.py | 963 | 4.03125 | 4 | thislist = ["apple", "banana", "cherry"]
if "banana" in thislist:
print("Yes")
else:
print ("No")
# Phạm vi chỉ số chỉ định
print ("*******************")
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[0:4])
# Thay đổi giá trị mặt hàng
print ("********************")
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
# Copy một danh sách
print("**********************")
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
mylist.append("cat")
mylist.insert(2, "dog")
print("Danh sách trước khi copy: ",thislist)
print("Danh sách sau khi copy: ", mylist)
# Join two list
print("***********************")
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
# append list 2 into list 1
print("***********************")
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
|
0b84e4001ce3fde844003fa77106808cb43af93f | bbodo69/python | /basic02/list/List04.py | 209 | 3.578125 | 4 | # 리스트 속성
lst = [10,20,30,"abc","def"]
if 10 in lst:
print("10이 존재")
print("ad" not in lst)
lst = [1,2,3,[4,5,6]]
lst[-1][-1] = 100
print(lst)
# 리스트 연산자
lst = [0]*5
print(lst) |
c29278a1230604956dc315db57faa5f970fc491d | lozgarrido/waka | /libraries/shinypanda.py | 896 | 3.984375 | 4 | import pandas as pd
import numpy as np
def wipe_empty_columns(df, max_empty=0.7, exceptions=[]):
"""
Removes columns with too many empty values from a dataframe
Args:
df: Dataframe to clean
max_empty: the minimum percentage of valid values in a column (by default, 70%)
exceptions: list of names of columns that should not be deleted
Returns:
df: The cleaned dataframe
"""
# Convert empty strings into NaN
df = df.replace(r'^\s+$', np.nan, regex=True)
columns = list(df)
rows = len(df)
for column_name in columns:
if column_name in exceptions:
pass
else:
# Find NaN percentage
nan_percentage = (df[column_name].isna().sum() / rows)
if nan_percentage < max_empty:
pass
else:
del df[column_name]
return df
|
6e2c3697b4ef63776a72de0dedc39a052dad174f | Czy2GitHub/Python | /python_execOld/huatu.py | 126 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import turtle
t = turtle.Pen()
for x in range(90):
t.forward(x)
t.left(60)
turtle.done() |
47785ff8763c8ff1bb61f743e9d80c4b3048a3fa | daniel-grumberg/turtle-graphics | /projects/clock.py | 2,514 | 3.640625 | 4 | #! /usr/local/bin/python3
from turtle import *
from datetime import datetime
mode("logo")
speed(0)
seconds_turtle = Turtle()
minutes_turtle = Turtle()
hours_turtle = Turtle()
writer_turtle = Turtle()
writer_turtle.hideturtle()
old_day = -1
def draw_filled_triangle(hand, color, length):
hand.fillcolor(color)
hand.begin_fill()
hand.right(90)
hand.forward(length / 2)
hand.left(120)
hand.forward(length)
hand.left(120)
hand.forward(length)
hand.left(120)
hand.forward(length / 2)
hand.end_fill()
def draw_hand_shape(hand, head_color, length, head_length):
hand.pensize(3)
hand.forward(length)
draw_filled_triangle(hand, head_color, head_length)
def display_clockface(radius):
pensize(7)
for i in range(60):
penup()
forward(radius)
pendown()
if i % 5 == 0:
forward(25)
back(25)
else:
dot(3)
penup()
back(radius)
pendown()
right(6)
hideturtle()
def get_day_of_week_str(now):
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
return weekdays[now.weekday()]
def get_date_str(now):
months = [ "Jan.", "Feb.", "Mar.", "Apr", "May", "Jun.", "Jul.", "Aug", "Sep.", "Oct.", "Nov.", "Dec."]
return months[now.month - 1] + " " + str(now.day) + " " + str(now.year)
def display_date(now):
global old_day
writer_turtle.penup()
writer_turtle.forward(65)
day_of_week = get_day_of_week_str(now)
date_str = get_date_str(now)
if now.day != old_day:
writer_turtle.clear()
writer_turtle.write(day_of_week, align='center', font=('Courier', 14, 'bold'))
writer_turtle.back(150)
if now.day != old_day:
writer_turtle.write(date_str, align='center', font=('Courier', 14, 'bold'))
writer_turtle.forward(85)
old_day = now.day
def tick():
now = datetime.today()
seconds = now.second
minutes = now.minute + seconds / 60
hours = now.hour + minutes / 60
for turtle in seconds_turtle, minutes_turtle, hours_turtle:
turtle.reset()
display_date(now)
seconds_turtle.setheading(6 * seconds)
draw_hand_shape(seconds_turtle, 'red', 135, 25)
minutes_turtle.setheading(6 * minutes)
draw_hand_shape(minutes_turtle, 'blue', 125, 25)
hours_turtle.setheading(30 * hours)
draw_hand_shape(hours_turtle, 'green', 90, 25)
tracer(False)
ontimer(tick, 200)
display_clockface(160)
tick()
done()
|
d78775a7324a1664c3508c55df750260cbb9dd01 | iamanobject/Lv-568.2.PythonCore | /HW_9/Bodnar/Home_Work9_1.py | 335 | 4.09375 | 4 | try:
def age(x):
if x % 2 == 0 and x > 0:
return "Your age is even"
elif x % 2 == 1 and x > 0:
return "Your age is odd"
elif x < 0:
raise ValueError("Age can't have negative number")
x = int(input("Your age? "))
print(age(x))
except ValueError as e:
print(e) |
ca8b276944dfa4ea1883e363c7a9589ac00741d2 | EKU-Summer-2021/ml-assignment-beresgabor76 | /src/linear_regressor.py | 2,279 | 3.734375 | 4 | """
Module for Linear Regression class
"""
import os
import pandas as pd
from sklearn.linear_model import LinearRegression
from src.learning_algorithm import LearningAlgorithm
class LinearRegressor(LearningAlgorithm):
"""
Class for training a Linear Regression model, and then test it
"""
def __init__(self, saving_strategy, plotting_strategy):
"""
Constructor creates a LinearRegression model
"""
super().__init__(saving_strategy, plotting_strategy)
self.__lin_reg = LinearRegression()
self._is_scaled_x = True
self._parent_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'../results/linear_regression')
self._sub_dir = self._make_save_dir()
self._logger = self._setup_logger(f'LinearRegressionLog{self._sub_dir}',
os.path.join(self._parent_dir, self._sub_dir, 'run.log'))
def __correlation(self, dataset_x, dataset_y):
"""
Returns correlation values between input and output data
"""
dataset = pd.concat([dataset_x, dataset_y], axis=1)
corr_matrix = dataset.corr()
return corr_matrix['charges'].sort_values(ascending=False)
def train(self, train_set_x, train_set_y):
"""
Trains the LinearRegression model with passed data
"""
self.__lin_reg.fit(train_set_x, train_set_y)
self._logger.info('Correlation values with charges attribute in train set:')
self._logger.info('\n%s', self.__correlation(train_set_x, train_set_y))
def test(self, test_set_x, test_set_y, scaler):
"""
Tests the LinearRegression model with passed data
"""
self._copy_datasets(test_set_x, test_set_y)
self._x_scaler = scaler
score = self.__lin_reg.score(test_set_x, test_set_y)
self._logger.info('\nScore for test set: %f', score)
self._prediction = pd.DataFrame(self.__lin_reg.predict(test_set_x),
index=test_set_x.index,
columns=['prediction'])
self._prediction.reset_index(inplace=True)
self._prediction = self._prediction.drop('index', axis=1)
|
ed4ddaf9ea9282a0bc9f5e1c3fbbe5fdba55e2c9 | MotiAzran/next.py | /1-1-4.py | 146 | 3.5625 | 4 | import functools
def str_int_sum(a, b):
return int(a) + int(b)
def sum_of_digits(number):
return functools.reduce(str_int_sum, str(number))
|
5325a4cbeb8e26a647c498e6f4885bbeda3dc658 | zhonglinglong/pyqt5_demo | /python_isz_test/classDemo/myTime.py | 3,569 | 3.625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/1/10 14:25
# @Author : linglong
# @File : myTime.py
import calendar
import datetime
import time
class NewTime(object):
def __init__(self):
self.current_date = str(datetime.date.today())
self.current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
def _get_days_of_date(self, year, mon):
"""
内置函数:获取某年某月的天数
:param year: 年
:param mon: 月
:return: 当月天数
"""
return int(calendar.monthrange(int(year), mon)[1])
def _getyearandmonth(self, n=0, date=None):
"""
内置函数:获取当前月份
:param n: 已当前为标准,正整数往后加N月,负整数往前减N月
:param date:当前日 默认为空
:return:
"""
def addzero(n):
"""
把传入的字符串变成标准的月份 比如03 12
:param n: 传入的月份字符串
:return: 标准的月份显示字符串
"""
nabs = abs(int(n))
if (nabs < 10):
return "0" + str(nabs)
else:
return nabs
date = date if date else self.current_date
time = date.split('-')
thisyear, thismon = int(time[0]), int(time[1])
totalmon = thismon + n
if (n >= 0):
if (totalmon <= 12):
totalmon = addzero(totalmon)
return (time[0], totalmon, time[2])
else:
i = totalmon / 12
j = totalmon % 12
if (j == 0):
i -= 1
j = 12
thisyear += i
days = str(self._get_days_of_date(int(thisyear), j))
j = addzero(j)
return (str(thisyear), str(j), days if not date else time[2])
else:
if ((totalmon > 0) and (totalmon < 12)):
days = str(self._get_days_of_date(thisyear, totalmon))
totalmon = addzero(totalmon)
return (time[0], totalmon, time[2])
else:
i = totalmon / 12
j = totalmon % 12
if (j == 0):
i -= 1
j = 12
thisyear += i
days = str(self._get_days_of_date(thisyear, j))
j = addzero(j)
return (str(thisyear), str(j), days if not date else time[2])
def now_day(self, days=0, value=True):
if value:
date = str(datetime.date.today() + datetime.timedelta(days=days))
return date
else:
date = str(datetime.date.today() + datetime.timedelta(days=days))
dates = date + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))[10:20]
return dates
def now_month(self, months=0, date=None, value=True):
(y, m, d) = self._getyearandmonth(months) if not date else self._getyearandmonth(months, date)
arr = (y, m, d)
if (int(d) > self._get_days_of_date(int(y[0:4]), int(m))):
arr = (y[0:4], m, self._get_days_of_date(int(y), int(m)))
if value:
return (arr[0][0:4] + '-' + arr[1] + "-" + arr[2])
else:
return (arr[0][0:4] + '-' + arr[1] + "-" + arr[2]) + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))[10:20]
# t = NewTime()
# print(t.current_date)
# print(t.current_time)
# print(t.now_month(20, value=False))
|
14ef4a644ee20bb91a3da63332f01ccf559be736 | LiuJunb/PythonStudy | /book/section-2-基本数据类型/01-helloworld.py | 852 | 4.0625 | 4 | # 默认使用python3的语法
# 1.控制台输出
print ('hello world python3')
# 2.注释:
'''注释的第一种写法'''
# 注释的第二种写法
# 3.定义变量
message = 'liu jun'
first_name = 'liu'
last_name = 'jun'
full_name = first_name + ' ' + last_name
user_name = 'jack '
# 4.字符串常见的方法
print(message) # 输出结果 liu jun
print(message.title(), message.upper(), message.lower()) # Liu Jun LIU JUN liu jun
print(first_name + last_name) # 字符串的拼接
print(full_name) # liu jun
print(user_name) # jack
print(user_name.rstrip()) # 仅仅去除尾部的空格
# 还可以剔除字符串开头的空白 lstrip(),或同时剔除字符串两端的空白 strip()
# 5.制表符 和 换行符
print('message')
print('\nmessage') # 换行符号
print('\tmessage') # 制表符,缩进tab
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.