blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
81f61a0ba4f17cf20e443f759802fee974603019 | haojian/python_learning | /53. maximumSubarray.py | 342 | 3.890625 | 4 | '''
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.
'''
class Solution:
# @param {integer[]} nums
# @return {integer}
def maxSubArray(self, nums):
|
966c3fca1b3816ebd7773064d9762af72523708d | perovsk1te/python_practice | /Python_Lesson/class.py | 4,647 | 4 | 4 | """
objectはいらないがコードスタイル的に書いたほうがいい
コンストラクタ:__init__で初期化、インスタンスが出来た瞬間に実行される
デストラクタ:__del__, インスタンスがなくなるとき呼び出される
クラス全体で使いたい変数はself.paramとしてオブジェクト変数にする
クラス変数はすべてのオブジェクトで共有される
"""
class Person(object):
def __init__(self, name):
self.name = name
print(self.name)
def say_something(self):
print('Im {}'.format(self.name))
self.run(10)
def run(self, num):
print('run'*num)
def __del__(self):
print('Bye')
person = Person("Mike")
person.say_something()
del person
"""
継承
みんなで使う関数をまとめられる
上書きできる,superで親クラスを呼び出せる
@propertyで読み込み専用にできる、関数ではなくクラス変数として扱われる
@param.setterで特定の条件を満たしたときのみ書き換えられるようにする
"""
"""
抽象クラス
@abstractmethodがついたクラスは必ず継承する
多用しないほうが良い
"""
import abc
class Person(metaclass=ABCMeta):
def __init__(self, age=1):
self.age = age
@abc.abstractclassmethod
def drive(self):
pass
class Baby(Person):
def __init__(self, age=1):
if age < 18:
super().__init__(age)
else:
raise ValueError
def drive(self):
raise Exception('No drive')
class Adult(Person):
def __init__(self, age=18):
if age >= 18:
super().__init__(age)
else:
raise ValueError
def drive(self):
baby=Baby()
adult=Adult()
class Car(object):
def __init__(self, model = None):
self.model = model
def run(self):
print('run')
def ride(self, person):
person.drive()
car = Car()
car.ride(adult)
car.ride(baby)
class ToyotaCar(Car):
def run(self):
print('fast')
class TeslaCar(Car):
def __init__(self, model = 'Model s',
enable_auto_run=False,
password="123"):
#self.model = model
super().init(model)
#self.enable_auto_run = enable_auto_run
"""
アンダースコアが二個だとアクセスできなくなる、ただしクラス内
からはアクセスできる
"""
self._enable_auto_run = enable_auto_run
self.password = password
@property
def enable_auto_run(self):
return self._enable_auto_run
@enable_auto_run.setter
def enable_auto_run(self, is_enable):
if self.password == "456":
self.enable_auto_run = is_enable
else:
raise ValueError
"""
多重継承
関数名が被ったら左が優先
使わないほうが良い
"""
class Person(object):
def talk(self):
print('talk')
def run(self):
print('person run')
class Car(object):
def run(self):
print('run')
class PersonCar(Person, Car):
def fly(self):
print('fly')
"""
()をつけないとオブジェクトは生成されない(__init__が実行されない)
オブジェクトをつけなくてもクラス変数にはアクセスできる
@classmethodでクラスメソッドにできる、オブジェクトを生成しなくても呼び出せる
@staticmethodでs他ティックメソッドにできる、クラスの外に置いてもいいが
関連性がある場合はスタティックメソッドとして中に置いたほうがわかりやすい
"""
class Person(object):
kind = 'human'
def __init__(self):
self.age = 100
@classmethod
def what_is_your_kind(cls):
return cls.kind
@staticmethod
def about(year):
print('about human {}'.format(year))
a = Person()
b = Person
"""
特殊メソッド
__init__ コンストラクタ
__str__ オブジェクトを文字列として扱おうとしたときに呼ばれる
__len__ len(object)で呼び出される
__aadd__ オブジェクトの足し算
__eq__ オブジェクトの比較
"""
class Word(object):
def __init__(self, text):
self.text = text
def __str__(self):
return'Word!!!!'
def __len__(self):
return len(self.text)
def __add__(self, other):
self.text.lower() + other.text.lower()
def __eq__(self, other):
return self.text.lower() == other.text.lower()
w=Word('test')
print(len(w))
w2=Word('#########')
print(w + w2)
print(w == w2)
|
3358e4bebcd5a66359c2ce219684bddb6a191b76 | zhsomin/BP | /aa.py | 4,700 | 3.65625 | 4 | import tensorflow as tf
import cv2
import numpy as np
# 导入MNIST 数据集,不能直接下载的就先去官网下好,然后拖到工程目录下自己读取
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("input_data/", one_hot=True)
# 神经网络参数
num_input = 784 # mnist数据集里面的图片是28*28所以输入为784
n_hidden_1 = 256 # 隐藏层神经元
n_hidden_2 = 256
num_output = 10 # 输出层
# 模型类
class Model(object):
def __init__(self, learning_rate, num_steps, batch_size, display_step):
self.learning_rate = learning_rate # 学习率
self.num_steps = num_steps # 训练次数
self.batch_size = batch_size # batch大小
self.display_step = display_step # 日志打印周期
# 权重参数 注意此处不能讲权重全部初始化为零
self.weights = {
'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, num_output])),
}
# 偏置参数
self.biases = {
'h1': tf.Variable(tf.random_normal([n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([num_output])),
}
# 网络模型
def neural_net(self, input):
layer_1 = tf.add(tf.matmul(input, self.weights['h1']), self.biases['h1'])
layer_2 = tf.add(tf.matmul(layer_1, self.weights['h2']), self.biases['h2'])
out_layer = tf.add(tf.matmul(layer_2, self.weights['out']), self.biases['out'])
return out_layer
# 训练模型
def train(self):
# 占位符
X = tf.placeholder(tf.float32, shape=[None, num_input])
Y = tf.placeholder(tf.float32, shape=[None, num_output])
# 创建模型
logits = self.neural_net(X)
pred = tf.nn.softmax(logits)
# 损失函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
# 计算准确率
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 定义优化器
optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(loss)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
for step in range(1, self.num_steps + 1):
batch_x, batch_y = mnist.train.next_batch(batch_size=self.batch_size)
sess.run(optimizer, feed_dict={X: batch_x, Y: batch_y})
if step % self.display_step == 0 or step == 1:
loss_v, acc = sess.run([loss, accuracy], feed_dict={X: batch_x, Y: batch_y})
print("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss_v) + ", Training Accuracy= " + \
"{:.3f}".format(acc))
print("optimization finished!")
saver.save(sess, './model/neural_net.ckpt')
# 用测试集计算准确率
print("Testing Accuracy:", sess.run(accuracy, feed_dict={X: mnist.test.images,
Y: mnist.test.labels}))
# 评估函数 用来读入自定义的图片来验证模型的准确率
def evaluate(self, img_dir):
with tf.Session() as sess:
# 二值化处理
image = cv2.imread(img_dir, cv2.IMREAD_GRAYSCALE).astype(np.float32)
im = cv2.resize(image, (28, 28), interpolation=cv2.INTER_CUBIC)
img_gray = (im - (255 / 2.0)) / 255
cv2.imshow('out',img_gray)
cv2.waitKey(0)
img = np.reshape(img_gray, [-1, 784]) # -1表示不固定当前维度大小
# 恢复模型
saver = tf.train.Saver()
saver.restore(sess, save_path='./model/neural_net.ckpt')
# 识别
X = tf.placeholder(tf.float32, shape=[None, num_input])
Y = tf.placeholder(tf.float32, shape=[None, num_output])
# 创建模型
logits = self.neural_net(X)
pred = tf.nn.softmax(logits)
prediction = tf.argmax(pred, 1)
predint = prediction.eval(feed_dict={X: img}, session=sess)
print(predint)
if __name__ == '__main__':
model = Model(learning_rate=0.01, num_steps=5000, batch_size=128, display_step=100)
model.train()
model.evaluate("test.jpg")
|
5ad33c1e5167a998560bcbdfd1d8a6abc701ed85 | DenysSmyk/Python_Core | /lesson_11.py | 3,326 | 3.65625 | 4 | # 1. Спробуйте переписати наступний код через map.
# Він приймає список реальних імен і замінює їх хеш-прізвищами,
# використовуючи більш надійний метод-хешування.
# names = ['Sam', 'Don', 'Daniel']
# for i in range(len(names)):
# names[i] = hash(names[i])
# print(names)
# names = ['Sam', 'Don', 'Daniel']
# hash_name = map(hash,names)
# print(list(hash_name))
#2. Вивести список кольору “red”,
# який найчастіше зустрічається в даному списку
# [“red”, “green”, “black”, “red”, “brown”, “red”, “blue”, “red”, “red”, “yellow” ]
# використовуючи функцію filter.
# colors = ["red", "green", "black", "red", "brown", "red", "blue", "red", "red", "yellow" ]
# col_fix = filter(lambda x : x == "red", colors)
# print(list(col_fix))
# 3. Всі ці числа в списку мають стрічковий тип даних, наприклад [‘1’,’2’,’3’,’4’,’5’,’7’],
# перетворити цей список в список, всі числа якого мають тип даних integer:
# 1) використовуючи метод append
# lst_str = ['1','2','3','4','5','7']
# lst_int =[]
# for i in lst_str:
# lst_int.append(int(i))
# print(lst_str)
# print(lst_int)
#
# # 2) використовуючи метод map
# lst_str = ['1','2','3','4','5','7']
# lst_int =map(int , lst_str)
# print(lst_str)
# print(list(lst_int))
#4. Перетворити список, який містить милі , в список, який містить кілометри (1 миля=1.6 кілометра)
#a) використовуючи функцію map
# lst_km = [12, 25, 64]
# lst_m = map()
#b) використовуючи функцію map та lambda
# lst_m = [12, 25, 64]
# lst_km = map(lambda i: i * 1.6 , lst_m)
# print(list(lst_km))
#5. Знайти найбільший елемент в списку використовуючи функцію reduce
# from functools import reduce
# nums = [8, 2, 3, 6, 10, 1, 4]
#
# res = reduce(lambda a,b: a if a>b else b, nums)
# print(res)
# 6. Перепишіть наступний код, використовуючи map, reduce і filter. Filter приймає функцію і колекцію.
# Повертає колекцію тих елементів, для яких функція повертає True.
# people = [{'name': 'Sam', 'height': 160}, {'name': 'Alex', 'height': 80}, {'name': 'Jack'}]
# height_total = 0
# height_count = 0
# for person in people:
# if 'height' in person:
# height_total += person['height']
# height_count += 1
# print(height_total)
#map
# people = [{'name': 'Sam', 'height': 160}, {'name': 'Alex', 'height': 80}, {'name': 'Jack'}]
# height_total = map(lambda i: i["height"] if "height" in i else 0, people)
# print (sum(list(height_total)))
#reduse
from functools import reduce
people = [{'name': 'Sam', 'height': 160}, {'name': 'Alex', 'height': 80}, {'name': 'Jack'}]
height_total = reduce(lambda i, j: i["height"] if "height" in i else 0, people)
print (sum(list(height_total)))
|
7e04cb02050bfe656aa3ea63b58aedb4400ffe56 | DenysSmyk/Python_Core | /Basic subclasses - Adam and Eve.py | 267 | 3.5625 | 4 | def God():
return [ Man("Adam"), Woman("Eva") ]
class Human():
def __init__( self, name ):
self.name = name
class Man(Human):
def __init__( self, name ):
self.name = name
class Woman(Human):
def __init__( self, name ):
self.name = name
|
df20a66e9177f876f4407b90860596bb7efaf413 | DenysSmyk/Python_Core | /lesson_4.py | 3,870 | 3.8125 | 4 | #1. Роздрукувати всі парні числа менші 100
# (написати два варіанти коду: один використовуючи цикл while,
# а інший з використанням циклу for).
# for i in range(1,100):
# if i%2==0:
# print(i)
# i=2
# while i < 100:
# print(i)
# i+=2
# print(list(range(2,100,2)))
#2. Роздрукувати всі непарні числа менші 100.
# (написати два варіанти коду: один використовуючи оператор continue,
# а інший без цього оператора).
# for i in range(0,100):
# if i%2!=0:
# continue
# print(i)
#3. Перевірити чи список містить непарні числа.
# (Підказка: використати оператор break)
# l = [1,2,3,4,5,6,7,8,9,10]
# for i in l:
# if i%2==1:
# break
# print(i)
#4. Створити список, який містить елементи цілочисельного типу,
# потім за допомогою циклу перебору змінити тип даних елементів
# на числа з плаваючою крапкою.
#(Підказка: використати вбудовану функцію float ()).
# l = [1,2,3,4,5,6,7,8,9,10]
# for i in l:
# print(float(i),end=' ')
#5. Вивести числа Фібоначі включно до введеного числа n, використовуючи цикли.
# (Послідовність чисел Фібоначі 0, 1, 1, 2, 3, 5, 8, 13 і т.д.)
# fib = []
# a=1
# b=1
# for i in range(1,10):
# c=a+b
# fib.append(c)
# a=b
# b=c
# print(fib)
#6. Створити список, що складається з чотирьох елементів типу string.
# Потім, за допомогою циклу for, вивести елементи по черзі на екран.
# l =["a", "b", "c", "d"]
# for i in l:
# print(i)
#7. Змінити попередню програму так, щоб в кінці кожної букви
# елементів при виводі додавався певний символ, наприклад “#”.
# (Підказка: цикл for може бути вкладений в інший цикл,
# а також треба використати функцію print(“ ”, end=”%”)).
# l =["a", "b", "c", "d"]
# for i in l:
# print(i,end='#')
#8. Юзер вводить число з клавіатури, написати скріпт,
# який визначає чи це число просте чи складне.
# num = int(input('Введіть число: '))
# r_num= list(range(2,num))
# for i in r_num:
# if num % i == 0:
# print('{} - cкладне число'.format(num))
# break
# else:
# print('{} - просте число'.format(num))
#9. Знайти максимальну цифру дійсного числа.
# Дійсне число генеруємо випадковим чином за допомогою методу random() з модуля random
#(для цього підключаємо модуль random наступним чином from random import random)
# import random
#
# num = random.randint(10,1000)
# num_str = str(num)
# print(num)
# print(max(num_str))
#10. Визначити чи введене слово паліндром,
# тобто чи воно читається однаково зліва направо і навпаки.
# num = input('Введіть число: ')
# if num == num[::-1]:
# print('{} це число паліндром'.format(num))
# else:
# print('{} це число не паліндром'.format(num))
|
cdfb5c90d89acfcc3d2583a20247d2d1a314644e | yanhongqin001/python-exercise | /ex19.py | 669 | 3.578125 | 4 | def cheese_and_crackers(cheese_count,boxes_of_crackers):
print "You have %d cheeses!" %cheese_count
print "You have %d boxes of crackers!" %boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbles directly:"
cheese_and_crackers(20,30)
print "OR,we can use variables from our script:"
amount_of_cheese=10
amount_of_crackers=50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
print "We can even do math inside too:"
cheese_and_crackers(10 + 20,5 + 6)
print "And we can combine the two,variables and math:"
cheese_and_crackers(amount_of_cheese + 100,amount_of_crackers + 1000)
|
af565a02934dfc438ccb262507003bc24635f819 | yanhongqin001/python-exercise | /ex16.py | 679 | 4.0625 | 4 | # -*- coding: utf-8 -*-
from sys import argv
script,filename=argv
print "We're going to erase %r." %filename
print "If you don't want that,hit CTRL-C(^C)."
print "If you do want that,hit RETURN."
raw_input("?")
print "opening the file..."
target=open(filename,'w')
print "Truncating the file. Goodbye!"
#truncate-清空文件
target.truncate()
print "Now I'm going to ask you three lines."
line1=raw_input("line1:")
line2=raw_input("line2:")
line3=raw_input("line3:")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally,we close it."
target.close()
|
d6ba12bc3360f600651877f9109bdfd7db1c65ee | suheon/python-study | /7022.py | 1,275 | 3.65625 | 4 | # wikidocs/7022
string = 'abcdfe2a354a32a'
print(string.replace('a', 'A'))
string = 'abcd'
string.replace('b', 'B')
print(string)
a = "3"
b = "4"
print(a + b)
name1 = "김민수"
age1 = 10
name2 = "이철희"
age2 = 13
print("이름 : %s 나이 %d" % (name1, age1))
print("이름 : %s 나이 %d" % (name2, age2))
print("이름 : {} 나이 {}".format(name1, age1))
print(f"이름 : {name1} 나이 {age2}")
분기 = "2020/03(E) (IFRS연결)"
print(분기.split('(')[0])
print(분기[:7])
# box-sizing : border-box padding, border 까지 합이 width 로.
# 마진 상쇄, , 맞다은 box중 큰것으로.. 수직방향에서 마진 병합 현상이 일어난다.
# position : absolute 는 부모 중에 position: static 이 아닌 부분까지 거슬로 올라간다.
# id 선택자 > 클래스 선택자 > 태그 선택자
print("BTC_KRW".lower())
print("hello".capitalize())
file_name = "보고서.xlsx"
print(file_name.endswith('xlsx'))
print()
print(file_name.endswith(('xlsx', 'xls')))
file_name = "2020_보고서.xlsx"
print()
print(file_name.startswith('2020'))
a = "hello world"
print(a.split(' '))
movie_rank = ["닥터 스트레인지", "스플릿", "럭키"]
movie_rank.insert(1, '배트맨')
print(movie_rank)
print()
print()
print()
|
711895f2590aa58911073abb4914d25ae9320548 | AyeChanKoGH/Small-code- | /DrawPyV1.py | 1,686 | 4.46875 | 4 | """
get screen and drawing shape with python turtle
#To draw line, press "l" key and click first end point and second end point
#To draw circle, press "c" key and click the center point and click the quarent point
#To draw Rectangle, press "r" key and click 1st end point and second end point
#To clean the screen, press "delete" key.
"""
from turtle import*
import turtle
import time
import math
x=0
y=0
clicked=False
#To get the position of on screen click
def on_click(x,y):
global clicked
global po
po=[x,y]
clicked=Turtle
#To wait user point
def wait():
global clicked
turtle.update()
clicked=False
while not clicked:
turtle.update()
time.sleep(.1)
clicked=False
turtle.update()
#drawing turtle line
def line():
turtle.onscreenclick(on_click)
wait()
pu()
goto(po[0],po[1])
Fpo=po
pd()
turtle.onscreenclick(on_click)
wait()
goto(po[0],po[1])
#drawing circle
def dCircle():
turtle.onscreenclick(on_click)
wait()
pu()
goto(po[0],po[1])
Fpo=po
pd()
turtle.onscreenclick(on_click)
wait()
Spo=po
radi=math.sqrt(((Spo[0]-Fpo[0])**2)+((Spo[1]-Fpo[1])**2) )
pu()
goto(Fpo[0],Fpo[1]-radi)
pd()
circle(radi)
#drawing rectangular shape
def rectangle():
turtle.onscreenclick(on_click)
wait()
pu()
goto(po[0],po[1])
Fpo=po
pd()
turtle.onscreenclick(on_click)
wait()
Spo=po
goto(Spo[0],Fpo[1])
goto(Spo[0],Spo[1])
goto(Fpo[0],Spo[1])
goto(Fpo[0],Fpo[1])
#To clean the screen
def Sclear():
clear()
listen()
onkey(dCircle,"c")
onkey(rectangle,"r")
onkey(line,"l")
onkey(Sclear,"Delete")
mainloop()
|
caabee8f9fe7a3a83688350d57a52e833f5ec206 | blefmont/cisc352asgn1 | /alphabeta.py | 5,375 | 3.6875 | 4 | '''
Alpha-Beta Pruning
Authors: Michael Olson 20008033
: Brandon Christof 20014247
This program implements a minimax search algorithm that will determine
a score for any given state of a game. The search method uses Alpha-Beta
pruning to cut off any redudant searches to give a faster and
more efficient solution.
'''
## Global counter variable, counts the leaf nodes examined
counter = 0
## Node object, these are tree objects that have no value,
## can have children and can be root node
class Node():
## Constructor. Must be either MAX or MIN, can be a root and key is for debugging
def __init__(self, maxOrMin, isRoot = False, key = ""):
if (maxOrMin == "MAX"):
self.isMax = True
elif (maxOrMin == "MIN"):
self.isMax = False
else: raise ValueError('maxOrMin must be "MAX" or "MIN"')
self.isRoot = isRoot
self.key = key
self.children = []
## All tree objects must be able to say if they are root
def is_root_node(self):
return self.isRoot
## Max & Min accessors
def is_min_node(self):
return (not self.isMax)
def is_max_node(self):
return self.isMax
## Ability to add children
def add_child(self, node):
self.children.append(node)
## Returns a list of the objects that are it's children. Can be Nodes or Leafs
def get_children(self):
return self.children
## Leaf object, does not have max or min, children and can't be root
class Leaf():
## Constructor. Value is static evaluation, key is for debugging
def __init__(self, value):
self.value = value
self.key = str(value)
## Since Leaf is a tree object, must be able to say if it is root, but no leaves can be root
def is_root_node(self):
return False
## A recursive function that will search and return the highest/lowest
## score possible starting at a given root node.
## If at any point the value returned should be higher or lower than
## what their parent node is going to compare with, the sub search is
## immediately broken and returned. Since the child's lower/upper bound
## is greater than/less than their parents, it wouldn't matter what other
## choices their parent had.
def alpha_beta(current_node, alpha, beta):
global counter
## Check for root node, use 999999999 as infinity
if current_node.is_root_node():
alpha = -999999999
beta = 999999999
## Check if the tree object is of type Leaf
if type(current_node) == Leaf:
counter += 1
return current_node.value
## Use for loop for all children and use break as cut off search below
if current_node.is_max_node():
for a in current_node.get_children():
alpha = max(alpha, alpha_beta(a, alpha, beta))
if alpha >= beta:
break
return alpha
if current_node.is_min_node():
for b in current_node.get_children():
beta = min(beta, alpha_beta(b, alpha, beta))
if beta <= alpha:
break
return beta
## Deals with the file and returns content
def inputData(fileName):
with open(fileName) as f:
content = f.readlines()
return content
## Creates a new file with results
def outputData(results):
with open("alphabeta_out.txt", 'w') as f:
for line in results:
f.write(line)
f.close()
## Parse and init should get the line that defines the graph, and then
## it create all the nodes and link them together.
## returns the root node
def parse_n_init(graphstring):
nodeRef = dict()
# Sparates the two sections
nodesListString, nodesDataString = graphstring.split(' ')
# Clean the first string partially, and separate into items
nodesList = nodesListString[2:-2].split('),(')
# Init Root node
nodesList[0] = nodesList[0].split(',')
nodeRef[nodesList[0][0]] = Node(nodesList[0][1], True, key = nodesList[0][0])
rootNode = nodeRef[nodesList[0][0]]
# init other nodes
for i in range(1, len(nodesList)):
nodesList[i] = nodesList[i].split(',')
nodeRef[nodesList[i][0]] = Node(nodesList[i][1], key = nodesList[i][0])
# Clean data String
nodesData = nodesDataString[2:-2].split('),(')
# Create children and values
for i in range(len(nodesData)):
nodesData[i] = nodesData[i].split(',')
# if is a letter than add child
if (nodesData[i][1].isalpha()):
nodeRef[nodesData[i][0]].add_child(nodeRef[nodesData[i][1]])
# otherwise make it a leaf and give it a value
elif (nodesData[i][1].isnumeric()):
nodeRef[nodesData[i][0]].add_child(Leaf(int(nodesData[i][1])))
return rootNode
## Main function, ties all other functions together.
def main():
global counter
## read input data
content = inputData("alphabeta.txt")
results = []
## For every graph, parse string and run alpha_beta then collect results
for i in range(len(content)):
counter = 0
root = parse_n_init(content[i])
score = alpha_beta(root, None, None)
resultString = "Graph " + str(i+1) + ": Score: " + str(score) + "; Leaf Nodes Examined: " + str(counter) + '\n'
results.append(resultString)
outputData(results)
main()
|
12aeb6f87c3dda406422152ae6508bbeed6f61cb | Maria-Sparrow/Python_vebinars | /modules/models/My_Test_by.py | 1,365 | 4.0625 | 4 | from abc import ABC, abstractmethod
class AbstractParent(ABC):
@abstractmethod
def hello_friend():
raise NotImplementedError
class Mother(AbstractParent):
def init(self, age = 0):
self.age = age
print('Mother constructor!')
def cook_meal(self):
print("Hey, I was cooked dinner!")
def do_work(self):
print("I'm working")
def do_house_work(self):
print('listening music')
class Father(AbstractParent):
def init(self):
print('Father constructor!')
def play_guitar(self):
print('play guitar')
def do_house_work(self):
print('sitting on the sofa and drink beer')
class Daughter(Mother, Father):
def init(self, age = 0, name = None):
Mother.init(self, age=age)
Father.init(self)
def do_work(self):
print("I'm working like a horse!")
def cook_meal(self):
print("Hey,Can l help you?")
def hello_friend(self):
pass
class Friend:
pass
def greet_mother(mother : Mother):
print("Hello mother!!!")
mother.do_work()
def greet_father(father : Father):
print('time to beer!')
father.play_guitar()
if __name__ == "__main__":
daughter = Daughter()
#mother.do_work()
#change object class
#daughter.class = Friend
greet_mother(daughter)
greet_father(daughter)
daughter.hello_friend()
daughter.do_house_work()
daughter.cook_meal() |
274cedfbd8cad4d1293ebccdc015abde1a13d6d7 | AnDa-creator/Algorithms_Graph_algos | /MedianCalc.py | 2,592 | 3.546875 | 4 | from heapq import heapify, heappop, heappush
import csv
import time
def medianHeap(List_num):
new_list = List_num[:]
median = 0
heapify(new_list)
if len(new_list) >= 2:
# print('hi')
decider = len(List_num)
if decider % 2 == 0:
for number in range(decider//2 ):
# print(new_list)
# heapify(new_list)
median = heappop(new_list)
else:
for number in range(decider//2 + 1):
# print(new_list)
# heapify(new_list)
median = heappop(new_list)
# print(median)
return median
else:
return List_num[0]
def medianSearch(List_num):
new_list = List_num[:]
# print(new_list)
new_list.sort()
if len(new_list) == 1:
return new_list[0]
elif len(new_list) % 2 == 0:
return new_list[len(new_list) // 2 - 1]
else:
return new_list[len(new_list)//2 ]
if __name__ == '__main__':
time1 = time.time()
with open('median.txt', 'r') as test_file:
reader = csv.reader(test_file)
list_num = []
running_median = []
iterate_count = 0
for num in reader:
iterate_count += 1
list_num.append(int(num[0]))
new_median = medianHeap(list_num)
if iterate_count >= 200 and iterate_count % 200 == 0:
print("The new median: {} and iteration number is {}".format(new_median, iterate_count))
running_median.append(new_median)
time2 = time.time()
with open('median.txt', 'r') as test_file:
list_num2 = []
running_median2 = []
iterate_count2 = 0
reader2 = csv.reader(test_file)
for line in reader2:
iterate_count2 += 1
list_num2.append(int(line[0]))
new_median_2 = medianSearch(list_num2)
# print(new_median_2)
if iterate_count2 >= 200 and iterate_count2 % 200 == 0:
print("The new median(Search tree): {} and iteration number is {}".format(new_median_2, iterate_count2))
running_median2.append(new_median_2)
time3 = time.time()
final_sum = sum(running_median2)
print("Final sum in Search_case was {}".format(final_sum))
final_mod = final_sum % 10**4
print("Final value found is: {}".format(final_mod))
print("Time for heap case: {}".format(time2 - time1))
print("Time for Search case: {}".format(time3 - time2))
|
a2bcd1901a7e874d35263fc20ca61875c64aa07d | kimit956/MyRepo | /Code_Fixed.py | 1,942 | 3.859375 | 4 | def is_num(question):
while True:
try:
x = int(input(question))
break
except ValueError:
print("That is not a number")
continue
return x
class cat():
def __init__(self):
self.name = input("\nWhat is your pet's name?\n")
self.type = input(f"What type of pet is {self.name}?\n").lower()
self.color = input(f"What color is {self.name}?\n").lower()
self.age = is_num(f"How old is {self.name}?\n")
def main():
pet = [] #Creates empty array with name 'pet'
response = "y"
name = input("Hello! What is your name?\n")
while response != "n": #Will keep asking the user if they have a pet untill they type 'n'
pet.append(cat())
while True:
response = input("\nDo you have another pet? Y|n: ").lower()
if response == "y" or response == "":
break
elif response == "n":
break
else:
print("\nYou did not make a correct response, please use a 'Y' for yes and a 'n' for no.") #Will tell user that they did not enter a correct response
continue
num_pets = len(pet)
with open('My_Pet_List.txt','w') as file: #will allow editing of My_Pet_List and it will be known as 'file'
if num_pets == 1:
file.write(f"{name} has one pet, it's name is {pet[0].name}.\n\n")
else:
file.write(f"{name} has {num_pets} pets. Those pet's names are:")
count = 0
for i in pet:
count += 1
if count == 1:
file.write(f" {i.name}")
elif count != 1:
file.write(f", {i.name}")
file.write(".\n\n")
for i in pet:
file.write(f"{i.name} is a {i.color} {i.type} and is {i.age} years old.\n")
if __name__ != "__main__":
main()
else:
exit
|
fa085d5bace6c4496c002a929a41548604227ebb | kimit956/MyRepo | /Simple Math.py | 402 | 4.125 | 4 |
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
sum1 = num1 + num2
diff1 = num1 - num2
prod1 = num1 * num2
try:
divide1 = num1 / num2
except ZeroDivisionError:
num2 = int(input("Cannot divide by 0. Please enter a different number: "))
divide1 = num1 / num2
print("Sum:", sum1, "\tDifference:", diff1, "\tProduct:", prod1, "\tQuotient:", divide1) |
aad8fc25fc8901a2ad8c3f430aaae53ebbfe0e25 | jschmidt345/FinishedChallenges | /ch3/ch3_solution.py | 2,766 | 3.71875 | 4 | # need a list of all outings, cost of all outings, total cost of all outings
# Events : golf, bowling, amusment park, concert
# Aspects : # of attendees, date, total cost per person, total cost of event
# display of all the outings
# add individual outings
# calculations:
# display combined cost of all outings
# display of outing costs by type
#display all outings : event date, event cost, head count of attendee, cost per person
# 1 12-1-19 -> Bowling -> 1000.00 -> 50 -> 20
# outing add view :
# see cost of outings :
#cost per outing:
# cost by type, or total cost
# conditional : list all events that matched
# tuple input format
# use count
class Content:
def __init__(self, event_type, num_attendees, cost, month, day, year):
self.event_type = event_type
self.num_attendees = num_attendees
self.cost = cost
self.month = month
self.day = day
self.year = year
def __repr__(self):
return f'''
Event # of Attendees Cost Date
{self.event_type} {self.num_attendees} ${self.cost} {self.month}/{self.day}/{self.year}
'''
class Content_Data:
def __init__(self):
self.event_list = []
def show_list(self):
return(self.event_list)
def add_event(self, event_type, num_attendees, cost, month, day, year):
new_event = Content(event_type, num_attendees, cost, month, day, year)
self.event_list.append(new_event)
def __repr__(self):
return f'cost : {self.event_list}'
def get_event_cost(self, event_type):
total = 0
for i in self.event_list:
if i.event_type == event_type:
total += i.cost
return total
def get_total_cost(self):
total_cost = 0
for i in self.event_list:
total_cost += i.cost
return total_cost
def get_cost_per_person(self, event_type):
total_cost = 0
total_head_count = 0
for i in self.event_list:
if i.event_type == event_type:
total_cost += i.cost
total_head_count += i.num_attendees
return total_cost / total_head_count
#event type like accident type
#display total cost
#display cost per outing
#for i in event_list:
#if i[1] == 'golf':
#total += i[0]
#"i.event_type = golf"
# from pretty table import PrettyTable
#events = [('Justin team', 'win', 'all of them'),('jacob team', 'loss', '5 points')]
#x.field_names = ['team', 'outcome', 'total points']
#for i in events:
# x.add_row(list(i))
#x = PrettyTable()
# x.field_names('Team', 'Outcome', 'Total Points')
|
dfd0a5c903718388a8522f07d5919ffaac84a66f | spd94/Marvellous_Infosystem_Assignment_2 | /Assingment2_6.py | 207 | 3.78125 | 4 | def print_pattern_desc(n):
i=n
print("Output :")
while(i>0):
j=i
while(j>0):
print("*",end=" ")
j-=1
print("")
i-=1
print("Input :",end=" ")
x=int(input())
print_pattern_desc(x) |
72c900ad1d5f79614bd04a6c04b80df94c54a566 | nbe519/PythonEmailClient | /email.py | 3,352 | 4.09375 | 4 | #Noah Eaton
#Exploring Computer Science
#Email Client
#An email application which will take the subject, who it is to and
#the time and tell the user that the email has been sent.
#Import the module
from tkinter import *
import tkinter.messagebox
from tkinter import font
import datetime
import webbrowser
#Pull the current time but only the hour and minute
time = datetime.datetime.time(datetime.datetime.now())
time = time.strftime("%I:%M %p")
time = str(time)
#A function for the button in which when clicked will run through the following code
def sendEmail(sent,subject):
#collect the math problem then change it into an integer
math = entMath.get()
math = int(math)
#If the users answer is 4 and their is a sender present, send the message and clear the text boxes
if math == 2 + 2 and len(entSend.get()) > 0:
robotlbl.configure(text="You are not a robot!")
#Pull a pop-up screen which tells the user that the message sent
tkinter.messagebox.showinfo(title="Email Sent", message="Your email with the subject, %s, has been sent to %s at %s " %(sent, subject, time))
#Clear the text fields
entSend.delete(0, 'end')
entsub.delete(0, 'end')
entComp.delete(0, 'end')
entMath.delete(0, 'end')
#If the user has an incorrect answer or has no sender, fix the user fields
else:
robotlbl.configure(text="Email could not sent, make sure every field is filled out and filled correctly.")
url = 'https://www.gmail.com'
new = 1
def openGmail():
button(webbrowser.open(url, new=new))
#Create the tkinter window
window = Tk()
window.title("Nmail")
window.configure(bg="gray")
window.geometry("500x775")
#bring helvetica font into tkinter
appHighlightFont = font.Font(family='Helvetica', size=12)
#Email Title/Header
title = Label(window, text="Welcome to ", bg="gray")
title.config(font=('Helvetica', 32))
title.grid(row=0, column=30)
title.pack()
#Add an image below the title
imgpath = r"NMail.gif"
img = PhotoImage(file=imgpath)
photoLabel = Button(window, image=img, command= lambda: Button(webbrowser.open(url, new=new)))
photoLabel.pack()
#Sender Label
lblS = Label(window, text="To:", bg="gray")
lblS.grid(row=1, column=0)
lblS.pack()
#Entry for Sender
entSend = Entry(window,relief=SUNKEN, bd=4)
entSend.configure(font=appHighlightFont)
entSend.grid(row=3, column=0)
entSend.pack()
#Label for the subject
lblsub = Label(window, text="Subject: ", bg="gray")
lblsub.grid(row=4, column=0)
lblsub.pack()
#Entry box for subject
entsub = Entry(window, relief=SUNKEN, bd=4)
entsub.grid(row=1, column=1)
entsub.configure(font=appHighlightFont)
entsub.pack()
#Label for email box
lblCompose = Label(window, text="Compose Email Below", bg="gray")
lblCompose.grid(row=5, column=0)
lblCompose.pack()
#Text box for email
entComp = Text(window, relief=SUNKEN, bd=8)
entComp.configure(font=appHighlightFont)
entComp.pack()
#Math problem
lblMath = Label(window, text="To prove you are not a robot, what is 2 + 2", bg="gray")
lblMath.grid(row=6, column=0)
lblMath.pack()
entMath = Entry(window, relief=SUNKEN, bd=4)
entMath.pack()
#The label which tells the user if they are a robot
robotlbl = Label(window, bg="gray")
robotlbl.pack()
#A button which will activate the function at line 20
btn = Button(window, text="Submit", command=(lambda: sendEmail(entsub.get(), entSend.get())))
btn.pack()
#Draw the scene
window.mainloop() |
f7dec414936dd36792a3163b3e7d28c829d91013 | doddthomas/tools | /print_ex.py | 2,402 | 3.6875 | 4 | """
Typically, a module has a description at the top giving a brief summary
of its functionality and/or some examples. This is housed in a `docstring`
(a block of text surrounded by three double quotation marks). Below is an
example of what I would write for this script:
Examples of how to print objects in Python.
This script demonstrates a few methods for printing objects in Python.
Topics covered:
- %-formatting
- str.format()
- f.strings
TODO:
* Code review this type of documentation.
* Remove below doc and replace with this. Or, vice versa.
"""
#-----------------------------------------------------------------------
#
# print_ex.py - a python script showing examples of printing
# objects in Python.
#
#--------------------- module history -----------------------------
#
# 01-DEC-18 : PTR XXXX, Created, Logan Thomas
#
#-----------------------------------------------------------------------
# Define dummy objects to print
name = 'Tina'
age = 35
hams = 2.5
# Old-school string formatting in Python: %-formatting
# This is not recommended by the official Python docs
print('Hello %s' % name)
# yields => 'Hello Tina'
print('Hello %s. You are %d years old and have eaten %.2f hams today.' % (name, age, hams))
# yields => 'Hello Tina. You are 35 years old and have eaten 2.50 hams today.'
# More recent string formatting (preferred instead of %-formatting)
print('Hello {}'.format(name))
# yields => 'Hello Tina'
print('Hello {}. You are {} years old and have eaten {} hams today.'.format(name, age, hams))
# yields => 'Hello Tina. You are 35 years old and have eaten 2.5 hams today.'
# Can switch indexes to print with str.format
print('Hello {0}. You are {2:.2f} years old and have eaten {1} hams today.'.format(name, age, hams))
# yields => 'Hello Tina. You are 2.5 years old and have eaten 35 hams today.'
# Most recent (Python 3.6 and above) and most preferred: f-strings.
print(f'Hello {name}')
# yields => 'Hello Tina'
print(f'Hello {name}. You are {age} years old and have eaten {hams:.2f} hams today.')
# yields => 'Hello Tina. You are 35 years old and have eaten 2.5 hams today.'
# f-strings support arbitrary expressions
print(f'{5*3}')
# yields => 15
# f-strings support function evaluations
def shout(name):
return name.upper() + '!!!'
print(f'{shout(name)} Eat your food!')
# yields => 'TINA!!! Eat your food!'
|
082482fa78f6de049b03599a88b13a895788b765 | doddthomas/tools | /dog_name_list_ex.py | 662 | 4.0625 | 4 | #-----------------------------------------------------------------------
#
# dog_name_list_ex.py - a python script showing examples of dynamically
# adding items to an array/list
#
#--------------------- module history -----------------------------
#
# 12-OCT-18 : PTR XXXX, Created, Dodd M. Thomas
#
#-----------------------------------------------------------------------
dogNames = []
while True:
print('Enter dog name #' + str(len(dogNames)+1) + ' or [ENTER/RETURN] to exit=>',end=' ')
name = input()
if name =='':
break
dogNames = dogNames + [name]
print('Dog names:')
for name in dogNames:
print(name)
|
e14dde29a0ce84e90bfdef52902645337b9a1f46 | proth5150/Simple_Chatty_Bot | /Problems/Leap Year/main.py | 211 | 3.828125 | 4 | # put your python code here
year_to_check = int(input())
if year_to_check % 4 == 0 and year_to_check % 100 != 0:
print("Leap")
elif year_to_check % 400 == 0:
print("Leap")
else:
print("Ordinary") |
7051c6b60c42422cf8b0da06b23b36f5090ecb35 | robert-kolozsi/sequence_and_prime_numbers | /sum-prime-num.py | 2,987 | 3.9375 | 4 | #! /usr/bin/env python
# -*- conding:utf-8 -*-
l = []
for i in xrange(1, 8):
l.append(i)
print(l)
new_list = []
result_list = []
result_collection = []
#remain = []
first = None
def find_all():
global result_list
global result_collection
#if not result_collection:
# one_pass(l)
#else:
# one_pass(l)
one_pass(l)
one_pass(l)
one_pass(l)
def one_pass(the_list):
"""Recursive function."""
global first
global result_list
global result_collection
remain = []
#already_checked = False
tmp_remain = the_list
if not first:
first = l[0] # If running for the first time per combination.
#else:
# The last element is used if we use recursion.
#first = the_list[-1]
for j in the_list:
if j not in result_list and first != j:
second = j
#print("first: " + str(first) + " ; second: " + str(second))
# This whole condition is ignored for the first pass.
if first == the_list[0] and result_collection and check_pair(first, second):
#print("already have collection")
#already_checked = True
remain.append(second)
continue
# this is for first pass
#print("no collection yet")
result = first + second
if is_prime(result):
if first not in result_list:
result_list.append(first)
result_list.append(second)
first = result_list[-1]
else:
remain.append(second)
# This is out of loop.
# If we didn't finished the pass start recursion.
if remain and remain != tmp_remain:
#print("recursion")
one_pass(remain)
else:
result_collection.append(result_list)
first = None
second = None # Not sure if this has any affect?
result_list = []
remain = []
#already_checked = False
#print result_collection
def check_pair(first, second):
#print("first: " + str(first) + " ; second: " + str(second))
for element in result_collection:
#if element[:2] == [first, second]:
if element[0] == first and element[1] == second:
return True
return False
def print_is_prime():
"""Print only the prime numbers from given list."""
for i in l:
yes_prime = is_prime(i)
if yes_prime:
print(str(i) + ' is a prime number.')
def main():
#print_is_prime()
#do_the_math()
find_all()
def is_prime(number):
if number < 2:
return False
if number == 2:
return True
if not number & 1:
return False
# This algorithm is called Sieve of Eratosthenes
for x in xrange(3, int(number**0.5) + 1, 2):
if number % x == 0:
return False
return True
if __name__ == '__main__':
main()
print result_collection
|
ad0e3a2b253ccb2b869fe21dbe25ccfd0320a582 | NweHlaing/Python_Learning_Udemy_Course | /Section_20_Advanced_Python_obj_datastructures/advanced_list.py | 936 | 4.28125 | 4 | list1 = [1,2,3]
#append
list1.append(4)
print("list after appand..",list1)
#count
count = list1.count(10)
count1 = list1.count(2)
print("list count..",count)
print("list count 1..",count1)
#append and extend
x = [1, 2, 3]
x.append([4, 5])
print("append...",x)
x = [1, 2, 3]
x.extend([4, 5])
print("extend...",x)
#index
print("index2...",list1.index(2))
#insert
list1.insert(2,'inserted')
print("list1 after insert...",list1)
#pop
ele = list1.pop(1)
print("list1 in pop...",list1)
print("pop ...",ele)
#remove
print("list before remove...",list1)
list1.remove('inserted')
print("list after remove...",list1)
list2 = [1,2,3,4,3]
list2.remove(3)
print("list2 after remove...",list2)
#reverse
print("list2 before reverse...",list2)
list2.reverse()
print("list2 after reverse...",list2)
#sort
print("list2 before sort...",list2)
list2.sort()
print("list2 after sort...",list2)
|
9dea0287692cf96acc769688ec728c23a97b2ab5 | NweHlaing/Python_Learning_Udemy_Course | /Section_14_Advanced_Python_Modules/datetime_module.py | 292 | 3.6875 | 4 | import datetime
t = datetime.time(4, 20, 1)
today = datetime.date.today()
print(today)
# Let's show the different components
print(t)
print('hour :', t.hour)
print('minute:', t.minute)
print('second:', t.second)
print('microsecond:', t.microsecond)
print('tzinfo:', t.tzinfo) |
f57866cf75f296a3b531c7b9b98defbad635b52d | FatMaus/Py-Practice | /单链表.py | 4,113 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 26 18:07:39 2020
@author: Administrator
"""
# 链表节点,存储元素本身和下一个元素的信息(指针)
class Node():
# 值与下一个的地址,两个属性(单链表)
def __init__(self, elem, nextEle=None):
self.elem = elem
self.nextEle = nextEle
# 链表
class LinkListNode():
# 首位头元素、末位尾元素,长度三个属性
def __init__(self, head=None, tail=None, size=0):
self.head = head
self.tail = tail
self.size = size
# 增加元素(末位增加)
def append(self, number:int):
newNode = Node(number)
# 没有元素的时候直接添加到头,且头尾相同
if self.size == 0:
self.head = newNode
self.tail = self.head
self.size += 1
return
# 有头无尾,变成尾
elif self.tail == None:
self.tail = newNode
# 有头有尾,直接变成尾
else:
self.tail.nextEle = newNode
self.tail = newNode
self.size += 1
# 按位置索引插入元素
def insert(self, position:int, number:int):
# 防止索引超出报错
if position > self.size:
return
newNode = Node(number)
# 首位添加
if position == 0:
newNode.nextEle = self.head
self.head = newNode
if self.tail == None:
self.tail = newNode
self.size += 1
# 末位添加直接调用append方法
elif position == self.size:
self.append(number)
# 其他位置添加
else:
prev = self.head
for i in range(position):
prev = prev.nextEle
newNode.nextEle = prev.nextEle
prev.nextEle = newNode
self.size += 1
# 按值查找索引(不存在则返回-1)
def getIndex(self, number:int):
cur = self.head
for i in range(self.size):
if cur.elem == number:
return i
else:
cur = cur.nextEle
return -1
# 按值删除元素
def delete(self, number:int):
# 删除的是头元素时
if self.head.elem == number:
self.head = self.head.nextEle
self.size -= 1
# 删光时保证头尾相同
if self.size == 0:
self.tail = self.head
# 删除非头元素
else:
prev = self.head
cur = self.head
# 一位一位向后查找
while prev != None and cur != None:
if cur.elem == number:
# 若是尾元素直接去尾
if cur == self.tail:
self.tail = prev
# 非尾元素要进行指针交接,以免断点
prev.nextEle = cur.nextEle
self.size -= 1
return
# 继续向后匹配
prev = cur
cur = cur.nextEle
# 按新旧值更新元素(更改)
def update(self, old:int, new:int=old:int):
# 从头开始匹配
cur = self.head
for i in range(self.size):
# 匹配到直接更新值,然后返回索引
if cur.elem == old:
cur.elem = new
return i
# 不匹配继续推进匹配
else:
cur = cur.nextEle
# 遍历完仍未匹配到则返回-1
return -1
# 遍历元素,并装入数组打印
def display(self):
cur = self.head
printList = []
for i in range(self.size):
printList.append(cur.elem)
cur = cur.nextEle
print(printList)
# 简易测试
al = LinkListNode()
for i in range(10):
al.append(i)
al.display()
|
c20743ca806704d3cbdb98cb3bed95e4ebf7af61 | DeeCoob/hello_python | /_manual/format.py | 1,163 | 4.125 | 4 | # форматирование строки в стиле C s – форматная строка, x 1 …x n – значения
# s % x
# s % (x 1 , x 2 , …, x n )
# return Python has 002 quote types.
print("%(language)s has %(number)03d quote types." % {'language': "Python", "number": 2})
# '#' The value conversion will use the “alternate form” (where defined below).
# '0' The conversion will be zero padded for numeric values.
# '-' The converted value is left adjusted (overrides the '0' conversion if both are given).
# ' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
# '+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag).
# s.format(args) форматирование строки в стиле C#
print("The sum of 1 + 2 + {0} is {1}".format(1+2, 6))
print("Harold's a clever {0!s}".format("boy")) # Calls str() on the argument first
print("Bring out the holy {name!r}".format(name="1+3")) # Calls repr() on the argument first
print("More {!a}".format("bloods")) # Calls ascii() on the argument first |
dcd0873f0dbf3884fea27940dd7ca07bc9f2f902 | DeeCoob/hello_python | /_starter/03_elif.py | 266 | 4.125 | 4 | x = float(input("Enter x: "))
if 0 < x < 10:
print("Value is in range")
y = x ** 2 + 2 * x - 3
if y < 0:
print("y = ", y, "; y is negative")
elif y > 0:
print("y = ", y, "; y is positive")
else:
print("y = 0")
|
558c51cde6f1a6992bc7202b5b2cfbbd93e514f6 | DeeCoob/hello_python | /_tceh_lection/05_constructors.py | 688 | 4.28125 | 4 | # Constructor is called when new instance is create
class TestClass:
def __init__(self):
print('Constructor is called')
print('Self is the object itself', self)
print()
t = TestClass()
t1 = TestClass()
# Constructor can have parameters
class Table:
def __init__(self, numbers_of_legs):
print('New table has {} legs'.format(numbers_of_legs))
t = Table(4)
t1 = Table(3)
print()
# But we need to save them into the fields!
class Chair:
wood = 'Same tree'
def __init__(self, color):
self.color = color
c = Chair('green')
print(c, c.color, c.wood)
c1 = Chair('Red')
print('variable c did not change!', c.color)
print()
|
a5c80369e6ea000a2cf097a938200232583bf6e3 | DeeCoob/hello_python | /_manual/compares.py | 400 | 3.53125 | 4 | # x < y x строго меньше y
# x > y x строго больше y
# x <= y x меньше или равен y
# x >= y x больше или равен y
# x == y x равен y
# x != y x не равен y
# x is y x и y – это один и тот же объект
# x is not y x и y не являются одним и тем же объектом в памяти
|
97640a1a779bb561864b6d5db62e74cefe56b738 | DeeCoob/hello_python | /_practic/starter_02_two_words.py | 137 | 3.984375 | 4 | while True:
first = input("Enter first word: ")
second = input("Enter second word: ")
print(first, second, sep=', ')
|
d0922c3a88c57e9badfab0b28cc0294eb85eaefd | DeeCoob/hello_python | /_practic/starter_04_loop_factorial.py | 405 | 4.3125 | 4 | # Факториалом числа n называется число 𝑛!=1∙2∙3∙…∙𝑛.
# Создайте программу, которая вычисляет факториал введённого пользователем числа.
while True:
n = int(input("Enter n: "))
f = 1
for i in range(n):
f = f * (i + 1)
print("Factorial from n is", f)
|
cbbd3a4dbdd491594904e19541e506860badd28a | DeeCoob/hello_python | /_tceh_home_work/02_devision_by_seven.py | 226 | 3.78125 | 4 | # Пройти по всем числам от 1 до 100, написать в консоль, какие из них делятся на 7, а какие - нет
for i in range(1, 100):
if i % 7 == 0:
print(i)
|
2b77da4cba8b8bca5ae17bd3758edc7d1c311b1e | DeeCoob/hello_python | /_tceh_lection/05_classes.py | 1,248 | 3.90625 | 4 | class Car:
pass
c = Car()
print(c, type(c))
print()
# Classes can have variables called fields
class Room:
number = 'Room 34'
floor = 4
r = Room()
r1 = Room()
print(r.number, r1.number)
print(r.floor, r1.floor)
print()
# You can modify values:
r.number = 12
r.floor = '5 floor'
print(r.number, r1.number)
print(r.floor, r1.floor)
print()
# Classes can have functions inside: it called a met
class Door:
def open(self): # note that 'self' is the object
print('self is', self)
print('Door is opened')
self.opened = True
d = Door()
d.open()
print()
# Methods can accept params
class Terminal:
def hello(self, user_name):
print('Hello', user_name)
t = Terminal()
t.hello('Stas')
print()
class Terminal:
def __init__(self, user_name):
print('Hello', user_name)
t = Terminal('Stas')
t1 = Terminal('Sasha')
print()
# Classes can have both methods and fields
class Window:
is_opened = False
def open(self):
self.is_opened = not self.is_opened
print('Window is now', self.is_opened)
print()
w = Window()
w1 = Window()
print('Initial state', w.is_opened, w1.is_opened)
w.open()
print('New state', w.is_opened, w1.is_opened)
|
3905e28ea7425ad2b696a59df5194268f2882024 | frozen-dumplings/algorithm-playground | /JUMPGAME/hyowon.py | 876 | 3.5 | 4 | if __name__ == "__main__":
C = int(input())
for _ in range(C):
n = int(input())
inputMap = []
for _ in range(n):
inputMap.append(list(map(int, input().strip().split())))
reachable = [[False for i in range(n)] for i in range(n)]
reachable[0][0] = True
for i in range(n):
for j in range(n):
# print(i, j)
if reachable[i][j]:
if i + inputMap[i][j] < n:
reachable[i + inputMap[i][j]][j] = True
if j + inputMap[i][j] < n:
reachable[i][j + inputMap[i][j]] = True
# for i in range(n):
# print(reachable[i])
# print()
if reachable[n - 1][n - 1]:
print("YES")
else:
print("NO")
|
4d7086a59dd9e999d5e87259b696b583dd6cc839 | ETFIRE/ippsi_python | /fonction.py | 179 | 3.75 | 4 | #!/usr/bin/python3
def add(a, b):
"""function calcul addition"""
return(a+b)
print(add(1, 2))
print(add(10, 20))
def add3(a, b, c=0):
return(a + b + c)
print(add(1, 2))
|
98ed462b0bf705a87a4cb2bb3a9ea5093d908f00 | Sophie0829/2020-Jayden-AE401 | /猜猜看.py | 280 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 11:35:55 2020
@author: jaych
"""
#召喚模組
import random
num=random.randint(1,10)
a=input("請輸入數字:")
a=int(a)
if a==num:
print("恭喜你猜對了!")
else:
print("猜錯了!")
|
3d2a4044d6cc8831df8a97eca32532b10882d39d | lazear/quant | /vx_sourcing.py | 1,788 | 3.546875 | 4 | import pandas as pd
import numpy as np
import requests
import calendar
from datetime import timedelta, date
def third_wednesday(d, n):
"""Given a date, calculates n next third fridays
https://stackoverflow.com/questions/28680896/how-can-i-get-the-3rd-friday-of-a-month-in-python/28681097"""
def next_third_wednesday(d):
d += timedelta(weeks=4)
return d if d.day >= 15 else d + timedelta(weeks=1)
# Find closest wednesday to 15th of month
s = date(d.year, d.month, 21)
result = [s + timedelta(days=(calendar.WEDNESDAY - s.weekday()) % 7)]
# This month's third wednesday passed. Find next.
if result[0] < d:
result[0] = next_third_wednesday(result[0])
for i in range(n - 1):
result.append(next_third_wednesday(result[-1]))
return result
def download():
for d in third_wednesday(date(2013, 1, 1), 8*12):
s = "{}-{}-{}".format(d.year, d.month, d.day)
r = requests.get("https://markets.cboe.com/us/futures/market_statistics/historical_data/products/csv/VX/{}".format(s))
with open(s + '.csv', 'w+') as f:
f.write(r.text)
df = pd.DataFrame()
for d in third_wednesday(date(2013, 1, 1), 8*12):
csv = pd.read_csv("{}-{}-{}.csv".format(d.year, d.month, d.day))
n = csv['Futures'][0]
csv = csv.rename(columns={'Close': n})
if len(df) == 0:
df = csv[['Trade Date', n]]
else:
df = df.merge(csv[['Trade Date', n]], how='outer', on='Trade Date')
df.fillna(0, inplace='true')
df.to_csv('df.csv')
data = df.values.tolist()
with open('cleaned.csv', 'w+') as f:
f.write(','.join(['Trade Date'] + ['F{}'.format(x) for x in range(1, 10)]) + '\n')
for row in data[1:]:
f.write(','.join([str(x) for x in row if x != 0.0]) + '\n')
|
a5dd8877afd4da089e3e7932c903ca869116e040 | asansyzb/courses | /CS206 Data Structures/HW5/2b.py | 1,608 | 3.6875 | 4 | from ADT.tree import BinaryTree
from ADT.stack import Stack
from ADT.queue import Queue
file = open('stored.txt', 'r')
listTree = file.readline().strip().split()
#listTree = ['cat','apple','but','pull','line','food','me','say']
tree = BinaryTree(listTree[0]) #define the root
listTree.remove(listTree[0])
def BuildTree():
global listTree
stack = Stack()
stack.push(tree)
current = tree
for node in listTree:
if not stack.isEmpty():
if node<stack.top().getRootVal(): #store in left subtree
current.insertLeft(node)
current = current.getLeftChild()
stack.push(current)
else: #store in right subtree
while (not stack.isEmpty() and node>stack.top().getRootVal()):
current = stack.pop()
current.insertRight(node)
current = current.getRightChild()
stack.push(current)
def level_print(tree):
Parent_q = Queue()
Child_q = Queue()
Parent_q.enqueue(tree)
while not Parent_q.isEmpty():
while not Parent_q.isEmpty():
node = Parent_q.dequeue()
print(node.getRootVal(), end=' ')
if node.getLeftChild():
Child_q.enqueue(node.getLeftChild())
if node.getRightChild():
Child_q.enqueue(node.getRightChild())
print()
while not Child_q.isEmpty():
Parent_q.enqueue(Child_q.dequeue())
def main():
BuildTree()
level_print(tree)
main()
|
64d4fd7bb9e42b23ed08567a9d6ba23c5985e258 | lenssen/ps1 | /ps1c.py | 1,079 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 12:54:23 2020
@author: Lenssen
"""
down_payment = 0.25 * 1000000
current_savings = 0
starting_salary = int(input('Enter the starting salary: '))
low = 0
high = 10000
ans = (high + low ) // 2
steps = 0
portion_saved = 0
Answer = ''
while(abs(down_payment - current_savings) >= 100):
current_savings = 0
annual_salary = starting_salary
for month in range(1,37):
portion_saved = ans/10000
monthly_salary = annual_salary / 12
current_savings += (current_savings * (0.04 / 12)) + monthly_salary * portion_saved
if month % 6 == 0:
annual_salary += annual_salary * 0.07
if current_savings < down_payment:
low = ans
else:
high = ans
ans = (high + low ) // 2
if ans <= 0 or ans >= 9999:
Answer = 'No'
break
steps += 1
if Answer == 'No':
print('It is not possible to pay the down payment in three years.')
else:
print('Best savings rate:',portion_saved)
print('Steps in bisection search:',steps) |
f2621a6a490cb9f85aff73a741d44f11b5b0b28e | guoyang-xie/atom3d | /atom3d/util/file.py | 1,502 | 3.546875 | 4 | """File-related utilities."""
import os
from pathlib import Path
import subprocess
def find_files(path, suffix, relative=None):
"""
Find all files in path with given suffix. =
:param path: Directory in which to find files.
:type path: Union[str, Path]
:param suffix: Suffix determining file type to search for.
:type suffix: str
:param relative: Flag to indicate whether to return absolute or relative path.
:return: list of paths to all files with suffix sorted by their names.
:rtype: list[Path]
"""
if not relative:
find_cmd = r"find {:} -regex '.*\.{:}' | sort".format(path, suffix)
else:
find_cmd = r"cd {:}; find . -regex '.*\.{:}' | cut -d '/' -f 2- | sort" \
.format(path, suffix)
out = subprocess.Popen(
find_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=os.getcwd(), shell=True)
(stdout, stderr) = out.communicate()
name_list = stdout.decode().split()
name_list.sort()
return [Path(x) for x in name_list]
def get_pdb_code(path):
"""
Extract 4-character PDB ID code from full path.
:param path: Path to PDB file.
:type path: str
:return: PDB filename.
:rtype: str
"""
return path.split('/')[-1][:4].lower()
def get_pdb_name(path):
"""
Extract filename for PDB file from full path.
:param path: Path to PDB file.
:type path: str
:return: PDB filename.
:rtype: str
"""
return path.split('/')[-1]
|
23e115c87405a9b78f7c790981205d2fcd8a9c5a | bt14/social-distancing-simulation | /button.py | 2,789 | 3.5 | 4 | import pygame
# this file contains the Button and ButtonSet classes
class Button:
def __init__ (self, x, y, width, height, text, font, text_color, idle_color, hover_color, callback_funct, visible=True):
self.x = x
self.y = y
self.width = width
self.height = height
self.rect = pygame.Rect(x, y, width, height)
self.text = text
self.font = font
self.text_color = text_color
self.updateLabel()
self.idle_color = idle_color
self.hover_color = hover_color
self.callback_funct = callback_funct
self.hovered = False
self.outlineRect = (x-1, y-1, width+2, height+2)
self.outlineColor = (0,0,0)
self.visible = visible
def updateHover(self, mouse_pos):
self.hovered = False
if self.rect.collidepoint(mouse_pos):
self.hovered = True
# checks if it was clicked
def get_event(self, event):
if event.type == pygame.MOUSEBUTTONUP:
if self.hovered and self.visible:
self.callback_funct()
return True
return False
def updateLabel(self):
self.label = self.font.render(self.text, True, self.text_color)
self.label_rect = self.label.get_rect(center=self.rect.center)
def draw(self, win):
if self.hovered:
color = self.hover_color
else:
color = self.idle_color
pygame.draw.rect(win, self.outlineColor, self.outlineRect)
pygame.draw.rect(win, color, self.rect)
win.blit(self.label, self.label_rect)
class ButtonSet:
def __init__ (self, buttons, normal_idle_c, normal_hover_c, select_idle_c, select_hover_c, errorLbl, errorMsgPos):
self.buttons = buttons
self.normal_idle_c = normal_idle_c
self.normal_hover_c = normal_hover_c
self.select_idle_c = select_idle_c
self.select_hover_c = select_hover_c
self.selected = False
self.selectedVal = None # set by the buttons' callback functions
self.error = False
self.errorLbl = errorLbl
self.errorMsgPos = errorMsgPos
def draw(self, win):
if self.error:
win.blit(self.errorLbl, self.errorMsgPos)
for button in self.buttons:
button.draw(win)
def get_event(self, event):
for button in self.buttons:
clicked = button.get_event(event)
if clicked:
if button.idle_color == self.normal_idle_c:
self.buttonSelected(button)
else:
self.buttonDeselected(button)
def buttonSelected(self, button):
self.selected = True
self.error = False
button.idle_color = self.select_idle_c
button.hover_color = self.select_hover_c
for button2 in self.buttons:
if button2 != button:
button2.idle_color = self.normal_idle_c
button2.hover_color = self.normal_hover_c
def buttonDeselected(self, button):
self.selected = False
button.idle_color = self.normal_idle_c
button.hover_color = self.normal_hover_c
|
5f11f06276589e88a0946d273ddceca243504c60 | jxxiangwen/PythonStudy | /cn/edu/shu/design_mode/simple_factory.py | 1,267 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'jxxia'
"""
简单工厂模式
"""
class Operation(object):
def get_result(self, num1, num2):
pass
class AddOperation(Operation):
def get_result(self, num1, num2):
return num1 + num2
class SubOperation(Operation):
def get_result(self, num1, num2):
return num1 - num2
class MulOperation(Operation):
def get_result(self, num1, num2):
return num1 * num2
class DivOperation(Operation):
def get_result(self, num1, num2):
try:
result = num1 / num2
except ZeroDivisionError:
return 0
return result
class OperationFactory(object):
def __init__(self, ):
self.operation = dict()
self.operation['+'] = AddOperation()
self.operation['-'] = SubOperation()
self.operation['*'] = MulOperation()
self.operation['/'] = DivOperation()
def create_operation(self, operation):
return self.operation[operation]
if __name__ == '__main__':
print(OperationFactory().create_operation('+').get_result(1, 2))
print(OperationFactory().create_operation('/').get_result(1, 0))
assert (OperationFactory().create_operation('+').get_result(1, 2) == 3)
|
3baf3eff47106decb975eac235e777c39844021b | AbbadAnes/social_web_posts_to_mangodb | /modules/Database.py | 1,105 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 14:54:20 2020
@author: Anes ABBAD
@website : https://abbadanes.github.io/
"""
import pymongo
class Database():
def __init__(self, db_name="Jacques_chirac",client="mongodb://localhost:27017/"):
mangoclient = pymongo.MongoClient(client)
self.db_name = db_name
self.client = mangoclient
try :
_ = mangoclient[db_name]
print("Database created !")
except :
print("the database could not be created, are you sure that the client address is accessible?")
def create_collection(self,name="posts"):
try:
db = self.client[self.db_name]
col = db[name]
print("The collection : "+name+" is created in the Database : "+self.db_name)
except:
print("The collection could not be created")
return col
def store(self,collection,posts):
collection.insert_many(posts)
print(len(posts)," posts had been stored !")
|
bb9db30f7f466941ee6437f77f4ab20ac00c8e20 | vikramriyer/FCS | /infix_to_postfix.py | 2,075 | 4.09375 | 4 | #!/usr/bin/python
OUTPUT, STACK = [], []
precedence = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3
}
def is_operand(char):
if char.isalpha():
return True
return False
def check_precedence(char):
'''
check top and
return char if char has higher precedence
return top
'''
operator = ""
if STACK[-1] == '(':
STACK.append(char)
if precedence[STACK[-1]] >= precedence[char]:
operator = STACK.pop()
STACK.append(char)
else:
STACK.append(char)
return operator
def is_empty():
if len(STACK) == 0:
return True
return False
def calc_infix_to_postfix(expr):
'''
if the char is a operand i.e. an alphabet, then append to the output list
if the char is a '('
if the char is a '('
else which means the char is a operator, we compare with top and check
for precedence and append to the output list and pop the element
'''
for char in expr:
if is_operand(char):
OUTPUT.append(char)
elif char == '(':
STACK.append(char)
elif char == ')':
while not is_empty() and STACK[-1] != '(':
temp = STACK.pop()
OUTPUT.append(temp)
if (not is_empty() and STACK[-1] == '('):
print "Error in expression!"
exit(0)
else:
if not is_empty():
OUTPUT.append(check_precedence(char))
else:
STACK.append(char)
while not is_empty():
OUTPUT.append(STACK.pop())
def main():
calc_infix_to_postfix('a*(b-c)')
evaluate_postfix()
if __name__ == '__main__':
main()
OUTPUT = filter(None, OUTPUT)
print OUTPUT
if ['a','b','c','*','+'] == OUTPUT:
print "The postfix conversion is successful."
print "Postfix Expression: {}".format(OUTPUT)
else:
print "Error in the covnersion."
'''
Stage 1: works for a+b*c and simple expressions without '(' or ')' => done
Stage 2: should work for associativity, now works only for precedence => done
Stage 3: should work for 'Stage 1' cases as well => not done
''' |
a34c861f7c41768a76883e7e6f59c7149f106f36 | vikramriyer/FCS | /rotate_image.py | 419 | 4.125 | 4 | #!/usr/bin/python
init_list = [[1,2,3],[4,5,6],[7,8,9]]
def rotate_matrix(matrix):
'''Algo:
First: take transpose of the matrix
Second: interchange row 0 and row 2
'''
matrix = zip(*matrix)
return swap_rows(matrix)
def swap_rows(matrix):
print matrix
row0, row2 = matrix[0], matrix[2]
matrix[0] = row2
matrix[2] = row0
return matrix
final_matrix = rotate_matrix(init_list)
print final_matrix
|
9f1dd55147d61f3a53dd1b6f5459dc8010962ce2 | vikramriyer/FCS | /searching.py | 984 | 4.0625 | 4 | #!/usr/bin/python
def sequential_search(alist, item):
# method 1, pythonic way
for i in alist:
if item == i:
return True
# method 2, c way
position = 0
found = False
while position < len(alist) and not found:
if alist[position] == item:
found = True
break
position += 1
return found
def binary_search(alist, item):
'''
take three pointers
start, mid, last
if element < mid, recursively call alist[:mid]
if element > mid, recursively call alist[mid+1:]
some more conditions:
if len(alist) is zero then return
'''
print "List is: {}".format(alist)
start = 0
last = len(alist) - 1
if len(alist) == 0:
return False
else:
mid = len(alist)/2
if alist[mid] == item:
return True
else:
if item < alist[mid]:
return binary_search(alist[:mid], item)
else:
return binary_search(alist[mid+1:], item)
alist = [1, 5, 9, 11, 200, 201, 551]
print binary_search(alist, 551) |
30fe876edf81a871f0209661f44e6c9be25193e7 | jonathanmendoza-tx/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/assignment/rpg_queries.py | 3,506 | 3.921875 | 4 | import sqlite3
import pandas as pd
!wget https://github.com/jonathanmendoza-tx/DS-Unit-3-Sprint-2-SQL-and-Databases/blob/master/module1-introduction-to-sql/rpg_db.sqlite3?raw=true -O rpg_db.sqlite3
#create connection
conn = sqlite3.connect('rpg_db.sqlite3')
cur = conn.cursor()
def question_one():
query_characters = """
SELECT COUNT(character_id)
FROM charactercreator_character
"""
cur.execute(query_characters)
total_characters = cur.fetchall()
print(f'There are {total_characters[0][0]} total characters')
def question_two():
query_cleric = """
SELECT COUNT(character_ptr_id)
FROM charactercreator_cleric
"""
cur.execute(query_cleric)
total_clerics = cur.fetchall()
print(f'There are {total_clerics[0][0]} total clerics')
query_fighter = """
SELECT COUNT(character_ptr_id)
FROM charactercreator_fighter
"""
cur.execute(query_fighter)
total_fighters = cur.fetchall()
print(f'There are {total_fighters[0][0]} total fighters')
query_mage = """
SELECT COUNT(character_ptr_id)
FROM charactercreator_mage
"""
cur.execute(query_mage)
total_mages = cur.fetchall()
print(f'There are {total_mages[0][0]} total mages')
query_necromancer = """
SELECT COUNT(mage_ptr_id)
FROM charactercreator_necromancer
"""
cur.execute(query_necromancer)
total_necromancers = cur.fetchall()
print(f'There are {total_necromancers[0][0]} total necromancers')
query_thief = """
SELECT COUNT(character_ptr_id)
FROM charactercreator_thief
"""
cur.execute(query_thief)
total_thievs = cur.fetchall()
print(f'There are {total_thievs[0][0]} total thievs')
def question_three():
query_armory = """
SELECT COUNT(item_id)
FROM armory_item
"""
cur.execute(query_armory)
total_items = cur.fetchall()
print(f'There are {total_items[0][0]} total items')
def question_four():
query_weapons = """
SELECT COUNT(item_ptr_id)
FROM armory_weapon
"""
cur.execute(query_weapons)
total_weapons = cur.fetchall()
items_not_weapons = total_items[0][0] - total_weapons[0][0]
print(f'There are {total_weapons[0][0]} total weapons')
print(f'There are {items_not_weapons} items that are not weapons')
def question_five():
query_char_items = """
SELECT COUNT(item_id), character_id
FROM charactercreator_character_inventory
GROUP BY character_id
"""
cur.execute(query_char_items)
items_per_char = cur.fetchall()
items_df = pd.DataFrame(items_per_char, columns = ['num_of_items', 'char_id'])
items_df = items_df.set_index('char_id', verify_integrity = True)
print(items_df.head(20))
def question_six_to_eight():
query_char_weapons = """
SELECT COUNT(item_id), character_id
FROM charactercreator_character_inventory
WHERE item_id IN
(
SELECT item_ptr_id
FROM armory_weapon
)
GROUP BY character_id
"""
cur.execute(query_char_weapons)
weapons_per_char = cur.fetchall()
weapons_df = pd.DataFrame(weapons_per_char, columns = ['num_of_weapons', 'char_id'])
weapons_df = weapons_df.set_index('char_id', verify_integrity = True)
print(weapons_df.head(20))
item_count = list(zip(*items_per_char))[0]
avg_items_per_char = sum(item_count)/ total_characters[0][0]
print(f'There are an average of {avg_items_per_char} items per character')
weapon_count = list(zip(*weapons_per_char))[0]
avg_weapons_per_char = sum(weapon_count)/total_characters[0][0]
print(f'There are an average of {avg_weapons_per_char} weapons per character')
question_one()
question_two()
question_three()
question_four()
question_five()
question_six_to_eight()
|
20c5ba89af7ddd5f98b71c79e2062c2b36156bdc | Ashwin4010/MAS | /cost.py | 1,620 | 3.6875 | 4 | """
COST FUNCTION FOR AUTO TUNING OF PID CONTROLLER
"""
def sum_lists(l1,l2):
""" Arguments: list1, list2 """
l = []
for i in xrange(len(l1)):
l.append(l1[i]+l2[i])
return l
def dot_multiply(l, k):
""" Arguments: list, scalar """
l[:] = [x * k for x in l]
return l
def cost(theta, sigma_err):
""" theta = [Kp, Ki, Kd] """
# step (step of sum TBD?):
dt = 0.01
""" sigma_err = sum of errors -> integral/sum function
-> These sums are gained in the code. """
# Compute the integral:
t0 = 0
tf = 1
J = (1/(tf - t0))*(sigma_err **2)*dt
return J
def autotune(theta):
# weight how much the parameters are changed each iteration:
a = 0.1
# Compute derivative with respec to first parameter:
delta = 0.01
var = [1, 0, 0]
derivative = (cost(theta + dot_multiply(var,delta)) - cost(theta - dot_multiply(var,delta)))/(2 * delta)
""" SIMULATION: theta = [Kp Ki Kd] => sim(theta) """
theta_new = theta - dot_multiply(derivative,a) #a*derivative
print theta_new
return theta_new
def dot_multiply(l1, k):
""" Arguments: list, scalar """
ln = []
for j in l1:
pom = j*k
ln.append(pom)
return ln
if __name__ == "__main__":
theta = [1,2,3]
var = [1,0,0]
delta = 0.01
ls = []
ls.append(1)
print ls[0]
|
a192b7e4dd1b255a4fd1aebf4a0c241ec2eaeb8b | hg387/Data-Structures-Algo | /Trees/huffman.py | 2,645 | 3.640625 | 4 | #!/usr/bin/env python
#we make the class for base tree of nodes here
class tree:
def __init__(self,left,right,parent):
self.parent = parent
self.left = left
self.right = right
#we make the class alphabet here
class alphabet:
def __init__(self,char,probability,leaf):
self.char = char
self.probability = probability
self.leaf = leaf
#we make the class forest here
class forest:
def __init__(self,weight,root):
self.weight = weight
self.root = root
#make function takes a value for left tree and right tree and returns the counter
def make(ltree,rtree):
counter = len(TREE)
TREE.append(tree(0,0,0))
TREE[counter].left = FOREST[ltree].root
TREE[counter].right = FOREST[rtree].root
TREE[counter].parent = 0
TREE[FOREST[rtree].root].parent = counter
TREE[FOREST[ltree].root].parent = counter
return counter
def lightones(one,two):
if FOREST[0].weight > FOREST[1].weight:
one =1
two = 0
else:
one = 0
two = 1
for i in range(2,len(FOREST)):
if FOREST[i].weight < FOREST[two].weight:
two = i
if FOREST[i].weight < FOREST[one].weight:
two = one
one = i
return (one,two)
def huffman():
temp1 = 0
temp2 = 0
counter_temp = len(FOREST)
#We use the huffman algorithm to obtain the minimum frequency nodes out of the min heap and replace the lowest two by a new node with the lowest two nodes as daughter nodes and repeat this.
while counter_temp > 1:
temp1, temp2 = lightones(temp1,temp2)
new = make(temp1,temp2)
FOREST[temp1].weight = FOREST[temp1].weight + FOREST[temp2].weight
FOREST[temp1].root = new
FOREST[temp2] = FOREST[counter_temp-1]
del FOREST[counter_temp-1]
counter_temp = counter_temp - 1
return
ALPHABET = [alphabet('a',7,0), alphabet('b',9,1), alphabet('c',12,2), alphabet('d',22,3), alphabet('e',23,4), alphabet('f',27,5)]
TREE = [tree(0,0,0), tree(0,0,0), tree(0,0,0), tree(0,0,0), tree(0,0,0), tree(0,0,0)]
FOREST = [forest(7,0), forest(9,1), forest(12,2), forest(22,3), forest(23,4), forest(27,5)]
print("For the first run")
print("TREE would be equal:")
k=0
while(k<len(TREE)):
print(TREE[k])
k+=1
print("\n")
k=0
print("ALPHABET would be equal:")
while(k<len(ALPHABET)):
print(ALPHABET[k])
k+=1
print("\n")
k=0
print("FOREST would be equal:")
while(k<len(FOREST)):
print(FOREST[k])
k+=1
print("\n")
huffman()
print("Result would be:")
print("\n")
print("TREE would be equal:")
k=0
while(k<len(TREE)):
print(TREE[k])
k+=1
print("\n")
k=0
print("ALPHABET would be equal:")
while(k<len(ALPHABET)):
print(ALPHABET[k])
k+=1
print("\n")
k=0
print("FOREST would be equal:")
while(k<len(FOREST)):
print(FOREST[k])
k+=1
print("\n")
|
7b4455500f93ec009bdbbd4874b06b0e2f24bcb7 | hg387/Data-Structures-Algo | /Trees/levelorder.py | 655 | 3.734375 | 4 | #!/usr/bin/env python
# configuring the level order using pointer tree
from lcrstree import *
def levelorder(tree):
temp = []
count = tree.root()
temp.append(count)
while(len(temp) > 0):
print(temp[0].label())
node = temp.pop(0)
if node.left is not None:
temp.append(node.left)
if node.right is not None:
temp.append(node.right)
# Tree shape
# Printed the tree in order of a,b,c,d,e,f,g
# a
# / \
# b c
# / \ / \
# d e f g
T1 = Node("b")
T1.left = Node("d")
T1.right = Node("e")
T2 = Node("c")
T2.left = Node("f")
T2.right = Node("g")
T = create2("a",None,None)
T.left = T1
T.right = T2
levelorder(T)
|
4382434746bdf25d60f85b498f4c2cdbd8a9d0ae | hg387/Data-Structures-Algo | /ArrayListImpl/timing.py | 5,187 | 3.640625 | 4 | #!/usr/bin/env python
import timeit
from Pointerlist import *
from Arraylist import *
from Arraystack import *
from Pointerstack import *
# Insertion head for 3 cases
start = timeit.default_timer()
def array():
x = [None]*500
for i in range(0,500):
x.insert(i, i)
stop = timeit.default_timer()
print("Insertion Head standard list:" + str(stop-start) + "\n")
start = timeit.default_timer()
def head_array():
x = Arraylist()
for i in range(0,500):
x.insert(i,i)
stop = timeit.default_timer()
print("Insertion Head arraylist:" + str(stop-start) + "\n")
start = timeit.default_timer()
def head_pointer():
x = Pointerlist()
for i in range(0,500):
x.insert(i,i)
stop = timeit.default_timer()
print("Insertion Head pointerlist:" + str(stop-start) + "\n")
# Insertion tail for all three cases
start = timeit.default_timer()
def array_tail():
x = [None]*500
for i in range(0,500):
x.append(1)
stop = timeit.default_timer()
print("Insertion Tail standard list: " + str(stop - start) +"\n")
start = timeit.default_timer()
def tail_array():
x = Arraylist()
for i in range(0,500):
x.insert(1,x.end())
stop = timeit.default_timer()
print("Insertion Tail arraylist: " + str(stop - start) +"\n")
start = timeit.default_timer()
def tail_pointer():
x = Pointerlist()
for i in range(0,500):
x.insert(1,x.end())
stop = timeit.default_timer()
print("Insertion Tail Pointerlist: " + str(stop - start) +"\n")
# Transversal operation for three cases
start = timeit.default_timer()
def transversal_std_array():
x = [None]*500
for i in range(0,500):
new = x[i]
stop = timeit.default_timer()
print("Transversal standard list: " + str(stop - start) +"\n")
start = timeit.default_timer()
def transversal_array():
x = Arraylist()
for i in range(0,500):
x.insert(1,x.end())
element = x.first()
while element:
element = x.Next(element)
stop = timeit.default_timer()
print("Transverse arraylist: " + str(stop - start) +"\n")
start = timeit.default_timer()
def transversal_pointer():
x = Pointerlist()
for i in range(0,500):
x.insert(1,x.end())
element = x.first()
while element:
element = x.Next(element)
stop = timeit.default_timer()
print("Transverse Pointerlist: " + str(stop - start) +"\n")
# Deletion operation for three cases
start = timeit.default_timer()
def std_deletehead():
x = [None]*500
for i in range(0,500):
del x[0]
stop = timeit.default_timer()
print("Delete head standard list: " + str(stop - start) +"\n")
start = timeit.default_timer()
def deletehead_array():
x = Arraylist()
for i in range(0,500):
x.insert(1,x.first())
for i in range(0,500):
x.delete(0)
stop = timeit.default_timer()
print("Delete head arraylist: " + str(stop - start) +"\n")
start = timeit.default_timer()
def deletehead_pointer():
x = Pointerlist()
for i in range(0,500):
x.insert(1,x.first())
for i in range(0,500):
x.delete(0)
stop = timeit.default_timer()
print("Delete head Pointerlist: " + str(stop - start) +"\n")
# delete tail operation for three cases
start = timeit.default_timer()
def std_listdelete():
x=[None]*500
for i in range(0,500):
del x[-1]
stop = timeit.default_timer()
print("Delete tail standard list: " + str(stop - start) +"\n")
start = timeit.default_timer()
def deletetail_array():
x = Arraylist()
for i in range(0,500):
x.insert(1,x.end())
for i in range(0,500):
x.delete(0)
stop = timeit.default_timer()
print("Delete tail arraylist: " + str(stop - start) +"\n")
start = timeit.default_timer()
def deletetail_pointer():
x = Pointerlist()
for i in range(0,500):
x.insert(1,x.end())
for i in range(0,500):
x.delete(0)
stop = timeit.default_timer()
print("Delete head Pointerlist: " + str(stop - start) +"\n")
# push operation in all three cases
start = timeit.default_timer()
def array_stdstack():
x = []
for i in range(0,500):
x.append(i)
stop = timeit.default_timer()
print("Push arraystack: " + str(stop - start) +"\n")
start = timeit.default_timer()
def array_pushstack():
x = Arraystack()
for i in range(0,500):
x.push(i)
stop = timeit.default_timer()
print("Push arraystack: " + str(stop - start) +"\n")
start = timeit.default_timer()
def pointer_pushstack():
x = Pointerstack()
for i in range(0,500):
x.push(i)
stop = timeit.default_timer()
print("Push pointerstack: " + str(stop - start) +"\n")
# Pop elements operation in three cases
start = timeit.default_timer()
def stdarray_popstack():
x = []
for i in range(0,500):
x.append(i)
for i in range(0,500):
x.pop()
stop = timeit.default_timer()
print("Pop standard list: " + str(stop - start) +"\n")
start = timeit.default_timer()
def array_popstack():
x = Arraystack()
for i in range(0,500):
x.push(i)
for i in range(0,500):
x.pop()
stop = timeit.default_timer()
print("Pop arraylist: " + str(stop - start) +"\n")
start = timeit.default_timer()
def pointer_popstack():
x = Pointerstack()
for i in range(0,500):
x.push(i)
for i in range(0,500):
x.pop()
stop = timeit.default_timer()
print("Pop Pointerlist: " + str(stop - start) +"\n")
|
539b4b3c131c0a2fe3a8d48c4a484931e9f476da | robreinhold/goodbye | /tokenize.py | 2,460 | 3.5 | 4 | #!/usr/bin/python
from Crypto import Random
from Crypto.Cipher import AES
def pad(s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(message, key, key_size=256):
message = pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def decrypt(ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")
def encrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
enc = encrypt(plaintext, key)
with open(file_name + ".enc", 'wb') as fo:
fo.write(enc)
def decrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
return decrypt(ciphertext, key)
def tokenize_and_index(payload, token_list, payload_list):
for line in payload.splitlines():
for word in line.split():
word = word.replace("(", "").replace(")","")
if(word not in token_list):
token_list.append(word)
token_list.sort()
token_list.reverse()
token_list.insert(0,"")
for line in payload.splitlines():
word_list = []
for word in line.split():
word = word.replace("(", "").replace(")","")
word_list.append(token_list.index(word))
payload_list.append(word_list)
def print_tokenized_payload(token_list, payload_list):
for line in payload_list:
output = ""
for word in line:
output = output + " " + token_list[word]
print output
def print_golang_datastructs(token_list, payload_list):
print "\tvar token_list [{}]string".format(len(token_list))
for idx, token in enumerate(token_list):
print "\ttoken_list[{}] = \"{}\"".format(idx, token)
print "\n\tvar payload_list [{}][{}]int".format(len(payload_list),10)
for line_idx, line_elements in enumerate(payload_list):
for element_idx, element in enumerate(line_elements):
print "\tpayload_list[{}][{}] = {}".format(line_idx, element_idx, element)
key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'
payload = decrypt_file("./payload.enc", key)
token_list = []
payload_list = []
tokenize_and_index(payload, token_list, payload_list)
print_golang_datastructs(token_list, payload_list)
print_tokenized_payload(token_list, payload_list) |
b95977ac51a4ab6b1ff10dc07315e75cd2b75a5c | IanBurgan/EulerSolutions | /Problems 31-40/Euler37.py | 1,002 | 3.734375 | 4 | from math import sqrt
def main():
start = [2, 3, 5, 7]
odds = [1, 3, 5, 7, 9]
rights = []
truncs = []
# find 2 digit truncatables
for i in start:
for j in odds:
num = (i * 10) + j
if isPrime(num):
rights.append(num)
# find all right truncatables
for i in rights:
for j in odds:
num = (i * 10) + j
if isPrime(num):
rights.append(num)
# check all right truncatables for left truncatables
for i in rights:
if isLeft(i):
truncs.append(i)
print(sum(truncs))
def isLeft(number):
amount = 10
while number % amount != number:
if not isPrime(number % amount):
return False
amount *= 10
return True
def isPrime(number):
if number % 2 == 0 or number == 1:
return False
for i in range(3, int(sqrt(number) + 1), 2):
if number % i == 0:
return False
return True
main()
|
136d013945afc4a687b43499c4b9b8c488677cd4 | IanBurgan/EulerSolutions | /Problems 11-20/Euler12.py | 368 | 3.71875 | 4 | def main():
i = 2
num = 1
while factors(num) < 500:
num += i
i += 1
print(num)
# Will not return the correct number for perfect squares as it does not
# check the square root of the number.
def factors(num):
facs = 0
for i in range(1, int(num ** 0.5)):
if num % i == 0:
facs += 2
return facs
main()
|
fe1843915bfb35f0f0c9d10180936414ee47856f | IanBurgan/EulerSolutions | /Problems 41-50/Euler50.py | 1,654 | 3.671875 | 4 | def main():
# 546 is max length. sum(first 547 primes) > 1000000. not true for 546
num = 546
extra = 0
primes = nPrimes(num)
while not isPrime(sum(primes)):
if sum(primes) > 1000000:
extra = 0
num -= 1
extra += 1
primes = nPrimes(num + extra)
# removing bottom of sequence until it is correct length
for i in range(extra):
primes.discard(min(primes))
print(sum(primes))
# terrible way to generate n primes, but it works for this
def nPrimes(n):
limit = 6 * n
primes = sieve(limit)
while len(primes) > n:
limit -= 2
primes = sieve(limit)
while len(primes) < n:
limit += 2
primes = sieve(limit)
return primes
def sieve(limit):
primes = [True] * limit
primes[0], primes[1] = False, False
# eliminate all multiples of 2
for i in range(4, len(primes), 2):
primes[i] = False
# eliminate all multiples of primes
for (i, isPrime) in enumerate(primes):
if isPrime:
for j in range(i * i, limit, 2 * i):
primes[j] = False
return {x for x in range(len(primes)) if primes[x]}
def isPrime(n):
# base cases
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
# primes all take form of 6k + 1 or 6k - 1
# test by all numbers of this form (aka possible primes) below sqrt of n
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
main()
|
44be0001eb6cf6a67d74df935df74d62a0972df7 | IanBurgan/EulerSolutions | /Problems 21-30/Euler21.py | 479 | 3.6875 | 4 | from math import sqrt
def main():
total = 0
for i in range(1, 10000):
other = sumfactors(i)
if i == sumfactors(other):
if i != other:
total += i + other
print(total/2)
def sumfactors(x):
total = 1
for i in range(2, int(sqrt(x) + 1)):
# add all factors found to the total
if x % i == 0:
total += i
if i != x // i:
total += x // i
return total
main()
|
fe9c76b453494d5cf57e0c94c186345fa00a8898 | IanBurgan/EulerSolutions | /Problems 11-20/Euler16.py | 189 | 3.890625 | 4 | def main():
# the number
a = 2 ** 1000
a = str(a)
# loop over its digits adding them to total
total = 0
for i in a:
total += int(i)
print(total)
main()
|
f94bc8bab3f94884686eddfdc5fffd59f14f79a9 | IanBurgan/EulerSolutions | /Problems 31-40/Euler31.py | 543 | 3.671875 | 4 | def main():
target = 200
coins = [1, 2, 5, 10, 20, 50, 100, 200]
# 1 way to make 0 coins at first and 0 ways to make any more than 0
ways = [1] + [0] * target
for coin in coins:
# starts at coin because no amount less than the coin can be changed by
# using the coin.
for i in range(coin, target + 1):
# each amount can now be made by using the coin and any one of the
# ways to make the (amount - the coin)
ways[i] += ways[i - coin]
print(ways[-1])
main()
|
5892e586b601e5a5bda23d15770863fcf42efa68 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 025.py | 334 | 4.03125 | 4 | ret = 's'
while ret == 's' or ret == 'S':
nome = str(input('Digite aqui seu nome completo:\n')).strip()
nome = nome.upper()
if 'SILVA' in nome:
print('Você é só mais um SILVA que a estrela não brilha')
else:
print('Ui Ui Ui, o diferentão não é SILVA')
ret = input('Deseja continuar?(S/N)\n') |
b981bc547cea42c8216c30b17bbe64414428dd40 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 032.py | 217 | 3.84375 | 4 | print('Calculadora de ANOS BISSEXTOS')
year = int(input('Digite o ano para saber se ele é bissexto\n'))
if year % 4 == 0:
print('{} é BISSEXTO!'.format(year))
else:
print('{} NÃO é BISSEXTO!'.format(year)) |
c49d6a750d724b11f6c5f9514352f38e2fec6a5c | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 008.py | 126 | 3.828125 | 4 | med = int(input('Digite o valor em metros: '))
print('O valor em metros é de {}, {}cm, {}mm'.format(med, med*100, med*1000))
|
ba0e3aee2104495d693e988f744a31d9e72c18dd | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 097.py | 273 | 3.703125 | 4 | def escreva(x):
print('~' * (len(x) + 6))
print(f' {x} ')
print('~' * (len(x) + 6))
while True:
frase = str(input('Digite uma frase para o cabeçalho:\n'))
escreva(frase)
r = str(input('Digite N para parar: '))
if r in 'nN':
break
|
5571e4c1487ba8809b9542253200ca0b55da9b79 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 009.py | 310 | 3.8125 | 4 | n = int(input('Digite um número para saber sua tabuada: '))
print('-'*40)
print('Tabuáda de',n)
print('{}x1 = {} \n{}x2 = {} \n{}x3 = {} \n{}x4 = {} \n{}x5 = {} \n{}x6 = {} \n{}x7 = {} \n{}x8 = {} \n{}x9 = {} \n{}x10 = {}'.format(n, n, n, n*2, n, n*3, n, n*4, n, n*5, n, n*6, n, n*7,n ,n*8, n, n*9, n, n*10)) |
9c46d81429372ca326bede6be5360ebe04988898 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 004.py | 236 | 3.65625 | 4 | def Exercicio():
r1 = input('Digite algo: ')
print('É um número?')
print(r1.isnumeric())
print('É um texto?')
print(r1.isalpha())
print('É alfanúmerico?')
print(r1.isalnum())
Exercicio()
Exercicio()
|
7c1221999f6578c46dfabd3161ca29e070dc69b2 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 034.py | 190 | 3.859375 | 4 | sal = float(input('Qual o salário do funcionário?\nR$'))
if sal > 1250:
sal = sal * 1.10
else:
sal = sal * 1.15
print('O salário deste funcionário será de R${:.2f}'.format(sal)) |
d4ce020dee9b589b29a3df86b6cc87aa5890e145 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 038.py | 471 | 3.796875 | 4 | print('\033[34m-=\033[m'* 20)
print('Comparador numérico')
print('\033[34m-=\033[m'* 20)
n1 = float(input('Digite o primeiro número.\n'))
n2 = float(input('Digite o segundo número.\n'))
if n1 > n2:
print('O \033[4;32mPRIMEIRO\033[m valor digitado é \033[4;35mMAIOR\033[m')
elif n2 > n1:
print('O \033[4;32mSEGUNDO\033[m valor digitado é \033[4;35mMAIOR\033[m')
else:
print('\033[4;32mNÃO EXISTE\033[m valor maior, os dois são \033[4;35mIGUAIS\033[m!!') |
f61dbcd9c0e46cb3552b22d80b5c147f4bde105c | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 031.py | 242 | 3.75 | 4 | km = float(input('Qual é a distância do seu destino?\n'))
if km <= 200:
print('O valor de sua passagem é de R${:.2f}.'.format(km * 0.5))
else:
print('O valor de sua passagem é de R${:.2f}.'.format(km * 0.45))
print('Boa Viagem!!') |
ec2f496ad253da7711af0148278e611de8f14e05 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 100.py | 480 | 3.65625 | 4 | from random import randint
from time import sleep
def sorteia(lista):
print(f'Sorteando os valores da lista:', end=' ')
for c in range(0, 5):
n = randint(1, 10)
lista.append(n)
print(n, end=' ')
sleep(0.4)
print()
def somaPar(lista):
soma = 0
for n in lista:
if n % 2 == 0:
soma += n
print(f'A soma dos valores pares da lista é igual a {soma}!')
numeros = list()
sorteia(numeros)
somaPar(numeros)
|
f5ec335a61dd14d8e5de49a96e4711a573445546 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 081.py | 480 | 3.859375 | 4 | m_n = 'S'
lista = []
while m_n == 'S':
n = int(input('Digite um número: '))
lista.append(n)
m_n = str(input('Deseja continuar?(S/N): ')).upper()[0]
print('-=' * 30)
print(f'Foram digitados {len(lista)} números')
reverso = lista[:]
reverso.sort(reverse=True)
print(f'Os valores em ordem decrescente são {reverso}')
if 5 in lista:
print(f'Existe o valor 5 na lista na posição {lista.index(5) + 1}.')
else:
print('Não foi encontrado o número 5 na lista.')
|
8582a38d30b9bba7da38847b34d6d7446ac18d6d | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 019.py | 299 | 3.828125 | 4 | from random import choice
a1 = input('Digite o nome do primeiro aluno: ')
a2 = input('Digite o nome do segundo aluno: ')
a3 = input('Digite o nome do terceiro aluno: ')
a4 = input('Digite o nome do quarto aluno: ')
list = [a1, a2, a3, a4]
r = choice(list)
print('O aluno escolido foi {}'.format(r))
|
31479fa70e35eab299957a6e90052b36a8f53ab1 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 084.py | 944 | 3.640625 | 4 | pessoa = list()
grupo = list()
ac_peso = list()
ab_peso = list()
tot = 0
while True:
pessoa.append(str(input('Nome: ')).capitalize())
pessoa.append(float(input('Peso: ')))
grupo.append(pessoa[:])
pessoa.clear()
tot += 1
resp = str(input('Deseja continuar?(S/N): ')).upper()[0]
if resp == 'N':
break
print('-=' * 30)
print(f'Ao total foram {tot} pessoas cadastradas.')
for pessoa in grupo:
if pessoa[1] >= 100:
ac_peso.append(pessoa[0])
elif pessoa[1] <= 70:
ab_peso.append(pessoa[0])
if ac_peso == []:
print('Não existem pessoas acima dos 100 kg!')
else:
print('As pessoas acima de 100kg são: ', end = '')
for nome in ac_peso:
print(f'{nome}... ', end = '')
print('\n')
if ab_peso == []:
print('Não existem pessoas abaixo de 70kg')
else:
print('As pessoas abaixo de 70kg são: ', end = '')
for nome in ab_peso:
print(f'{nome}... ', end = '') |
56a71169c30888ad339d98cafd400ce9757acae9 | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 050.py | 180 | 3.9375 | 4 | soma = 0
for c in range(0, 6):
n1 = int(input('Digite um número\n'))
if n1 % 2 == 0:
soma += n1
print('Os valores pares digitados dão a soma de {}'.format(soma))
|
eeb55c9016e2e2d09d56b2bf680add73a85a3b6f | yanbernardo/exercicios-python-3 | /Exercícios/Desafio 066.py | 216 | 3.6875 | 4 | cont = s = 0
while True:
n = int(input('Digite um número(999 para PARAR):\n'))
if n == 999:
break
s += n
cont += 1
print(f'Foram digitados {cont} números e a soma entre eles é igual a {s}') |
74f15cf391919b14dabf1ec9a7c404ff73016e4f | GabeAboy/PythonScripts | /calc.py | 3,706 | 3.640625 | 4 | import Tkinter as tk
from Tkinter import Grid
class Calculator:
def __init__(self):
self.root = tk.Tk()
self.root.title("Calculator")
self.calcscreen = ''
self.calculator = tk.Button(bd=5,text=self.calcscreen,width=20)
self.calculator.grid(row=0,column=2)
self.label = tk.Label(text="Calculator by PixelHD").grid(row=1,column=1)
self.num1 = tk.Button(bd=5,text="1",command=self.add1)
self.num1.grid(row=2,column=0)
self.num2 = tk.Button(bd=5,text="2",command=self.add2).grid(row=2,column=1)
self.num3 = tk.Button(bd=5,text="3",command=self.add3).grid(row=2,column=2)
self.num4 = tk.Button(bd=5,text="4",command=self.add4).grid(row=3,column=0)
self.num5 = tk.Button(bd=5,text="5",command=self.add5).grid(row=3,column=1)
self.num6 = tk.Button(bd=5,text="6",command=self.add6).grid(row=3,column=2)
self.num7 = tk.Button(bd=5,text="7",command=self.add7).grid(row=4,column=0)
self.num8 = tk.Button(bd=5,text="8",command=self.add8).grid(row=4,column=1)
self.num9 = tk.Button(bd=5,text="9",command=self.add9).grid(row=4,column=2)
self.num0 = tk.Button(bd=5,text="0",command=self.add0).grid(row=5,column=1)
self.plus = tk.Button(bd=5,text="+",command=self.add).grid(row=2,column=3)
self.minus = tk.Button(bd=5,text="-",command=self.subtract).grid(row=3,column=3)
self.equal = tk.Button(bd=5,text="=",command=self.finishcalc).grid(row=4,column=3)
self.divide = tk.Button(bd=5,text="/",command=self.division).grid(row=4,column=0)
self.multiply = tk.Button(bd=5,text="*",command=self.multiplication).grid(row=4,column=2)
self.clear = tk.Button(bd=5,text="AC",command=self.clearcalc).grid(row=5,column=3)
self.root.mainloop()
def add1(self):
self.calcscreen += "1"
self.calculator.configure(text=self.calcscreen)
def add2(self):
self.calcscreen += "2"
self.calculator.configure(text=self.calcscreen)
def add3(self):
self.calcscreen += "3"
self.calculator.configure(text=self.calcscreen)
def add4(self):
self.calcscreen += "4"
self.calculator.configure(text=self.calcscreen)
def add5(self):
self.calcscreen += "5"
self.calculator.configure(text=self.calcscreen)
def add6(self):
self.calcscreen += "6"
self.calculator.configure(text=self.calcscreen)
def add7(self):
self.calcscreen += "7"
self.calculator.configure(text=self.calcscreen)
def add8(self):
self.calcscreen += "8"
self.calculator.configure(text=self.calcscreen)
def add9(self):
self.calcscreen += "9"
self.calculator.configure(text=self.calcscreen)
def add0(self):
self.calcscreen += "0"
self.calculator.configure(text=self.calcscreen)
def clearcalc(self):
self.calcscreen = ""
self.calculator.configure(text=self.calcscreen)
def add(self):
self.calcscreen += " + "
self.calculator.configure(text=self.calcscreen)
def subtract(self):
self.calcscreen += " - "
self.calculator.configure(text=self.calcscreen)
def finishcalc(self):
if self.calcscreen == "":
self.calcscreen = "0 + 0"
self.result = eval(self.calcscreen)
self.calculator.configure(text=self.result)
self.calcscreen = ""
def multiplication(self):
self.calcscreen += " * "
self.calculator.configure(text=self.calcscreen)
def division(self):
self.calcscreen += " / "
self.calculator.configure(text=self.calcscreen)
app = Calculator()
|
4c98e3e851f88b7c8e601f736a02b062c1e363c3 | LauFr/DataScienceDemoData | /Linear Regression/generate_data.py | 743 | 3.578125 | 4 | import numpy as np
import pandas as pd
N_obs = 1000
# create the city variable
city = np.random.randint(low=1, high=10, size=N_obs)
# create a variable with m^2
mu_m2, sigma_m2 = 100, 25 # mean and standard deviation
m2 = np.random.normal(mu_m2, sigma_m2, N_obs)
m2 = m2.round()
# create the age variable
mu_age, sigma_age = 80, 20 # mean and standard deviation
age = np.random.normal(mu_age, sigma_age, N_obs)
age = age.round()
# create the dependent variable (price)
price = 3*(city + np.random.randint(low=-1, high=1)) + 3000*m2 - 800*(age + np.random.randint(low=-1, high=1))
# create the train set
train = np.stack((city, m2, age, price), axis=1)
df = pd.DataFrame(train, columns=['City','m2','Age', 'Price']) |
470a73937a08e0b46fde63d5a2df2631e464016d | lfaipot/board-simu | /src/libproc.py | 1,680 | 3.625 | 4 | # -*- coding:utf-8 -*-
#
# Copyright(C) 2014 Laurent Faipot (laurent.faipot@free.fr). All rights reserved.
#
def ltoi(value, size):
"convert long integer into sized integer"
# value is extracted from memory without taking care of sign
# determine sign of integer
if (size <= 0):
return 0
mask = 1 << (size * 8 - 1)
if (value & mask):
# propagate sign bit
mask = -1 << (size * 8)
value = value | mask
else:
mask = -1 << (size * 8)
mask = ~mask
value = value & mask
return (value)
def ltoui(value, size):
"convert long integer into sized unsigned integer"
# mask: fulfill with 1 (setting to -1)
# just keep 1s on part to keep
mask = -1
mask = mask << (size * 8)
mask = ~mask
value = value & mask
#print "value: " + str(value) + " hex: " + str(ltoh(value, 4))
return value
def ltoa(value, size):
"convert long integer into ASCII of sized integer"
return str(ltoi(value, size))
def ltoh(value, size):
"convert long integer into HEX ASCII of sized integer"
value = ltoi(value, size)
nbits = size * 8
s = hex((value + (1 << nbits)) % (1 << nbits))
s = s[2:]
return s.rjust(size * 2, '0').upper()
def complement1(value, size):
#mask: must be 000..FF on part to keep
mask = -1
mask = mask << (size * 8)
mask = ~mask
res = ~value & mask
#print "COMPLEMENT1: size: " + str(size) + " mask: " + str(hex(mask)) + " value: " + str(hex(value)) + " res: " + str(hex(res))
return res
def complement2(value, size):
res = -value + 1
#print "COMPLEMENT2: value: " + str(hex(value)) + " res: " + str(hex(res))
return res |
ddbc01b74befc3cb94f28d9f0c23ea1392e7eadb | Rkhwong/RHK_CODEWARS | /Fundamentals - Python/Arrays/Convert an array of strings to array of numbers.py | 618 | 4.1875 | 4 | # https://www.codewars.com/kata/5783d8f3202c0e486c001d23
"""Oh no!
Some really funny web dev gave you a sequence of numbers from his API response as an sequence of strings!
You need to cast the whole array to the correct type.
Create the function that takes as a parameter a sequence of numbers represented as strings and outputs a sequence of numbers.
ie:["1", "2", "3"] to [1, 2, 3]
Note that you can receive floats as well."""
def to_float_array(arr):
new_list = []
for x in (arr):
(new_list.append(float(x)))
return new_list
print( to_float_array(["1.1", "2.2", "3.3"]) )
#RW 02/06/2021 |
6c3c745a5a9f7815a9a9a90f809417eee6a8238d | Rkhwong/RHK_CODEWARS | /Fundamentals - Python/Strings/The Office I - Outed.py | 1,517 | 3.984375 | 4 | #https://www.codewars.com/kata/the-office-i-outed
"""Your colleagues have been looking over you shoulder.
When you should have been doing your boring real job, you've been using the
work computers to smash in endless hours of codewars.
In a team meeting, a terrible, awful person declares to the group that you aren't working.
You're in trouble. You quickly have to gauge the feeling in the room to decide whether or not you should gather your things and leave.
Given an object (meet) containing team member names as keys, and their happiness rating out of 10 as the value,
you need to assess the overall happiness rating of the group. If <= 5, return 'Get Out Now!'. Else return 'Nice Work Champ!'.
Happiness rating will be total score / number of people in the room.
Note that your boss is in the room (boss), their score is worth double it's face value (but they are still just one person!)."""
def outed(meet, boss):
rating = 0
for x in meet:
if( x == boss):
rating = rating + meet[x]*2
else:
rating = rating + meet[x]
if ( rating / len(meet) <= 5):
return "Get Out Now!"
else:
return "Nice Work Champ!"
#test.assert_equals(, 'Get Out Now!')
outed({'tim':0, 'jim':2, 'randy':0, 'sandy':7, 'andy':0, 'katie':5, 'laura':1, 'saajid':2, 'alex':3, 'john':2, 'mr':0}, 'laura')
#RW 21/06/2021
#Other Solutions
def outed(meet, boss):
return 'Get Out Now!' if (sum(meet.values()) + meet[boss] ) / len(meet) <= 5 else 'Nice Work Champ!' |
714154207332e573cee0c4adfa95239ff0edf2e8 | MartynasIT/Pandas-csv-integrity-tester | /file_worker.py | 6,996 | 3.5625 | 4 | import pandas as pd
import main
import utils as util
def read_csv(file):
data = None
try:
data = pd.read_csv(file, error_bad_lines=False, warn_bad_lines=True, header=None)
print(util.get_filename(file) + ' red')
except Exception as e:
print(util.get_filename(file) + ' error due to' + str(e))
if check_if_header_exists(data):
data.columns = list(data.iloc[0])
data.drop(index=data.index[0], inplace=True)
return data
def save_csv(data, filename):
try:
data.to_csv(main.DIRECTORY_COMPARE / filename, index=False)
print('File fixed and saved as ' + filename)
except Exception as e:
print(util.get_filename(filename) + ' error due to' + str(e))
def check_column_count(sample_data, comparison_data):
count_col_sample = sample_data.shape[1]
count_col_comp = comparison_data.shape[1]
has_header_sample = check_if_header_exists(sample_data)
has_header_comp = check_if_header_exists(comparison_data)
if not has_header_comp and has_header_sample:
print('This file has no header')
comparison_data = override_columns(comparison_data, sample_data)
else:
if count_col_comp > count_col_sample:
print('This file has more columns than sample')
comparison_data = remove_col(sample_data, comparison_data)
elif count_col_comp < count_col_sample:
print('This file has missing columns compared to sample')
comparison_data = add_col(sample_data, comparison_data)
return comparison_data
def check_col_order(sample_data, comparison_data):
cols_sample = list(sample_data.columns)
cols_comparison = list(comparison_data.columns)
is_header_number_same = len(cols_sample) == len(cols_comparison)
if not is_header_number_same:
print('Files are different even after column removal')
return comparison_data
is_header_names_same = is_header_names_equal(cols_sample, cols_comparison)
is_data_same = check_row_values_same(sample_data, comparison_data, cols_sample, cols_comparison)
is_data_same_any_row = check_if_data_equal_ignoring_col_order(sample_data, comparison_data)
if is_data_same_any_row is not True:
raise ValueError('Files do not have same values')
elif is_header_names_same and not is_data_same or (
is_data_same is False and is_data_same_any_row):
print('This file has different column order')
comparison_data = reorder_columns(comparison_data, sample_data)
return comparison_data
def check_if_header_names_correct(sample_data, comparison_data):
cols_sample = list(sample_data.columns)
cols_comparison = list(comparison_data.columns)
is_header_names_same = is_header_names_equal(cols_sample, cols_comparison)
is_data_same = check_row_values_same(sample_data, comparison_data, cols_sample, cols_comparison)
if not is_header_names_same and is_data_same:
print('This file has different header values')
comparison_data = override_columns(comparison_data, sample_data)
elif not is_header_names_same and not is_data_same:
print('Files do not have same data')
return comparison_data
def check_if_header_exists(data):
first_row = list(data.columns)
for i, value in enumerate(first_row):
row = list(data.iloc[:, i])
k = 0
size_row = len(row)
type_header = type(value)
for row_val in row:
if type(row_val) == type_header and len(str(first_row[i])) <= len(str(row_val)):
k += 1
if k == size_row:
return False
return True
def reorder_columns(comparison_data, sample_data):
correct_order = []
for i, value in enumerate(comparison_data):
col_comp = comparison_data.iloc[:, i].values.tolist()
for j, val in enumerate(sample_data):
if sample_data.iloc[:, j].values.tolist() == col_comp:
correct_order.append(j)
comparison_data = comparison_data[[comparison_data.columns[q] for q in correct_order]]
comparison_data.columns = get_column_name_list(sample_data)
return comparison_data
def override_columns(comparison_data, sample_data):
cols_sample = get_column_name_list(sample_data)
comparison_data.columns = cols_sample
return comparison_data
def check_row_values_same(sample_data, comparison_data, cols_sample, cols_comparison):
eq_cal = 0
for i, j in zip(cols_sample, cols_comparison):
data_sample = sample_data[i].tolist()
date_comp = comparison_data[j].tolist()
number_cols = len(cols_sample)
if len(data_sample) == len(date_comp):
if set(data_sample) == set(date_comp):
eq_cal += 1
else:
return False
return eq_cal == number_cols
def is_header_names_equal(headers_sample, headers_comparison):
headers_sample = sorted(headers_sample)
headers_comparison = sorted(headers_comparison)
return headers_sample == headers_comparison
def get_column_name_list(data):
return list(data.columns)
def remove_col(sample_data, comparison_data):
cols_sample = get_column_name_list(sample_data)
cols_comparison = get_column_name_list(comparison_data)
to_remove = [x for x in cols_comparison if x not in cols_sample]
comparison_data.drop(columns=to_remove, inplace=True)
return comparison_data
def add_col(sample_data, comparison_data):
cols_sample = get_column_name_list(sample_data)
cols_comparison = get_column_name_list(comparison_data)
to_add = [x for x in cols_sample if x not in cols_comparison]
selected_cols = sample_data[to_add].copy()
return comparison_data.join(selected_cols)
def check_duplicate_headers(comparison_data):
cols_comparison = get_column_name_list(comparison_data)
for header in cols_comparison:
data_comp = comparison_data[header].tolist()
if header in data_comp:
print('Duplicate header found')
comparison_data = comparison_data[comparison_data[header] != header]
return comparison_data
def check_if_files_equal(data_sample, data_comp_dir):
if data_sample.columns.equals(data_comp_dir.columns):
if data_sample.head(3).equals(data_comp_dir.head(3)):
print('Files are equal')
return True
return False
def check_if_data_equal_ignoring_col_order(sample_data, comparison_data):
count = 0
for i, val in enumerate(comparison_data):
col_comp = list(comparison_data.iloc[:, i])
for j, value in enumerate(sample_data):
col_sample = list(sample_data.iloc[:, j])
if col_comp == col_sample:
count += 1
if count == len(get_column_name_list(sample_data)):
return True
return False
|
c800b5edcf4b5bd854046a4ac70906de884bdd96 | renarfreitas/Coursera | /indicadordepassagem.py | 420 | 4.09375 | 4 | decrescente = True
anterior = int(input("Digite o primeiro número da sequência: "))
valor = 1
while valor != 0 and decrescente:
valor = int(input("Digite o próximo número da sequência: "))
if valor > anterior:
decrescente = False
anterior = valor
if decrescente:
print("A sequência está em ordem decrescente! :-) ")
else:
print("A sequência não está em ordem decrescente! :-)") |
4321fb766b063af654d6fd2e5ef9ff73ff19536b | renarfreitas/Coursera | /pontos.py | 326 | 4 | 4 | import math
x = int(input("Informe o primeiro número: "))
y = int(input("Informe o segundo número: "))
x1 = int(input("Informe o terceiro número: "))
y1 = int(input("Informe o quarto número: "))
distancia = math.sqrt(((x - x1)**2) + ((y - y1)**2))
if distancia >= 10:
print("longe")
else:
print("perto") |
9435079619be61fcc486b27c067ef277e7e8a4a6 | renarfreitas/Coursera | /somadosdigitos.py | 197 | 3.765625 | 4 | import os
os.system('clear')
n = int(input("Digite o valor de n: "))
soma = 0
i = 1
while i <= n:
soma = soma + i
i = i + 1
print("A soma dos", n, "primeiros inteiros positivos é", soma) |
b2def4fe4337269c05c941cba3043e98e2f604e9 | renarfreitas/Coursera | /soma_digitos.py | 104 | 4.125 | 4 | num = int(input("igite um número inteiro: "))
i=0
while num:
i += num % 10
num //= 10
print(i) |
319f7b2578042fbd1ea15353e238323d8d4fda85 | Aka-Ikenga/Word-Cookies | /Cookies.py | 753 | 3.703125 | 4 | import itertools as it
import pprint as pp
def word_cookies(cookie):
with open('Common English Words.txt', 'r') as fh:
fh = fh.readlines()
valid_words = {i.strip() for i in fh} # a set containing all the words
cookies = {}
for i in range(3, len(cookie)+1):
# permutation produces invalid words, an intersection with the set of valid words will return
# the valid words produced by the permutation operation
words = {''.join(i) for i in it.permutations(cookie, i)} & valid_words
# there might be no valid words and permutation will return an empty set.
# no need to add them to the dictionary of cookies
if words != set():
cookies[f'{i} Letter Words'] = words
pp.pprint(cookies, indent=2)
word_cookies('Excellent')
|
d4b2fb6a0358c339c0e5dd7b85962a6ff00bd298 | maczoe/python_cardio | /convertidor.py | 921 | 4.21875 | 4 |
def convert_km_to_miles(km):
return km * 0.621371
def convert_miles_to_km(miles):
return miles * 1.609344;
def main():
print("Bienvenido a convertidor.py")
seleccion = 0;
while seleccion!=3:
print("----MENU----")
print("1. Millas a kilometros")
print("2. Kilometros a millas")
print("3. Salir")
seleccion = int(input("seleccion: "))
if(seleccion==1):
miles = float(input("Ingrese la cantidad en millas: "))
print(str(miles) + " milla(s) equivale a "+ str(convert_miles_to_km(miles)) + " Kms")
elif(seleccion==2):
km = float(input("Ingrese la cantidad en kilometros: "))
print(str(km) + " kilometro(s) equivale a "+ str(convert_km_to_miles(km)) + " millas")
elif(seleccion!=3):
print("Opcion invalida")
if __name__ == '__main__':
main()
|
6db0e37c33b66bdce65db37de937472922f082fd | senasaccount/python101 | /inheritance.py | 528 | 3.828125 | 4 | #using of __init__(self) with inheritance
class employee():
def __init__(self):
self.firstName = ""
self.lastName = ""
self.address = ""
class dataScience(employee):
def __init__(self):
self.language = ""
class marketing(employee):
def __init__(self):
self.storytelling = ""
nurkiz = dataScience()
nurkiz.firstName = "nurkiz"
nurkiz.lastName = "yildiz"
nurkiz.address = "aydin mahallesi"
nurkiz.language = "python"
nurkiz.lastName
nurkiz.language
|
c0acfdcd25c8f4116a2566404d68e5d18142c670 | ki4070ma/leetcode | /atcoder/20200503_ABC/A_.py | 135 | 4.0625 | 4 | #!/usr/bin/python3
for _ in range(1):
S = input().rstrip()
if S == "ABC":
print("ARC")
else:
print("ABC")
|
c2c84a63e80a92d29359689a7b4cc61f624f229e | ki4070ma/leetcode | /atcoder/20200126_ABC/D_.py | 1,094 | 3.5625 | 4 | #!/usr/bin/python3
from sys import stdin
# 1 -> 1 attack
# 2 -> 3
# 3 -> 3
# 4 -> 7
# 5
for _ in range(8):
H = int(input().rstrip())
ret = 0
if H == 1:
ret = 1
elif H in [2, 3]:
ret = 3
else:
count = 0
while H != 1:
H = H // 2
count += 1
ret = 3
print(count)
for i in range(count - 1):
ret = 2 * ret + 1
print(ret)
# def calc(target_monster_hitpoint, monster_list, dict_calc, cost):
# if target_monster_hitpoint == 1:
# cost += 1
# return monster_list, dict_calc, cost
# else:
# if target_monster_hitpoint in dict_calc.keys():
# pass
#
#
# for _ in range(8):
# H = int(input().rstrip())
# l = [H]
# d = {}
# ret = 0
# while len(l) > 0:
# hit_point = l.pop()
# if hit_point in d.keys():
# ret += d[hit_point]
# else:
# if hit_point == 1:
# ret += 1
# else:
# tmp = hit_point // 2
# l.extend([tmp, tmp])
|
8f1e12e3834caf2bea29812ece170c4c47770318 | ki4070ma/leetcode | /atcoder/20200613_ABC/A_.py | 81 | 3.625 | 4 | #!/usr/bin/python3
for _ in range(1):
S = input().rstrip()
print(S[:3])
|
e03b921c142c61bae48b5fdf5d345e08555ca019 | ki4070ma/leetcode | /atcoder/20200307_ABC/D_.py | 802 | 3.75 | 4 | #!/usr/bin/python3
for _ in range(3):
S = input().rstrip()
Q = int(input().rstrip())
reversed = False
from collections import deque
q = deque()
q.extend(list(S))
for _ in range(Q):
l = input().rstrip()
if l.startswith("1"):
reversed = False if reversed else True
else:
_, F, C = l.split()
if F == "1":
if reversed:
q.append(C)
else:
q.appendleft(C)
elif F == "2":
if reversed:
q.appendleft(C)
else:
q.append(C)
ret = "".join(list(q)[::-1]) if reversed else "".join(list(q))
print(ret)
assert ret == input().rstrip()
print(input().rstrip())
|
25a658c562e7bdce94d75292182b101d5eab787b | ki4070ma/leetcode | /leetcode/Easy/1108_Defanging_an_IP_Address.py | 328 | 3.5 | 4 | class Solution:
def defangIPaddr(self, address: str) -> str:
ret = ""
for n in address:
if n == ".":
ret += "[.]"
else:
ret += n
return ret
return "[.]".join(address.split(".")) # the fastest
return address.replace(".", "[.]")
|
898a2e111d2333ed77e0bff46acb7301573c9e74 | Mohan-Zhang-u/NLPDemoServer | /MyFlaskBackEnd/TextSummarization/capitalize.py | 2,818 | 3.9375 | 4 | import os
import sys
import argparse
import nltk
import codecs
'''
This python script is searching for any words in the original news article that are capitalized and not the first word
in a sentence, then replace the lower cased version of them in the summaries.
Also, it replace every word in the summaries that is the first word in a sentence to be capitalized.
'''
def capitalize(args):
original_news = os.listdir(args.original_news_path)
summmaries = os.listdir(args.summarization_path)
to_write=''
for summary in summmaries:
with codecs.open(os.path.join(args.original_news_path, summary), "r", encoding='utf-8') as fo:
with codecs.open(os.path.join(args.summarization_path, summary), "r", encoding='utf-8') as fs:
to_be_replaced = []
original_text = fo.read()
original_text_sentences = nltk.tokenize.sent_tokenize(original_text)
original_words = sum([i for i in [sentence.split()[1:] for sentence in original_text_sentences]], [])
for original_word in original_words:
if original_word.lower() != original_word:
if original_word[-1] == '.':
original_word = original_word[:-1]
to_be_replaced.append(original_word)
summary_text = fs.read()
summary_text_sentences = nltk.tokenize.sent_tokenize(summary_text)
for i in range(len(summary_text_sentences)):
summary_text_sentences[i] = summary_text_sentences[i][0].upper()+summary_text_sentences[i][1:]
summary_words = sum([i.split() for i in summary_text_sentences], [])
for word in to_be_replaced:
if word.lower() in summary_words:
for i in range(len(summary_words)):
if word.lower() == summary_words[i]:
summary_words[i] = word
# a = summary_text_sentences[0].split() + summary_text_sentences[1].split()
b=''
for i in summary_words:
if i != '.':
b += ' '
b += i
b = b[1:]
to_write = b
with codecs.open(os.path.join(args.summarization_path, summary), "w", encoding='utf-8') as fs:
fs.write(b)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Capitalize those words that should be capitalized.')
parser.add_argument('--summarization_path', required=True, help='path to summarization')
parser.add_argument('--original_news_path', required=True, help='path to original news')
args = parser.parse_args()
capitalize(args) |
4e2945720be75987b2c6633ca35992f4544ad7fa | LubosKolouch/hackerrank | /regex/british_american2.py | 277 | 3.6875 | 4 | import re
my_str = ' '.join([input() for _ in range(int(input()))])
for _ in range(int(input())):
word = input()
am_word = re.sub('ou', 'o', word, 0)
count = len(re.findall(word+r'\b', my_str))
count += len(re.findall(am_word+r'\b', my_str))
print(count)
|
b3377c885ed75c6b29457e119232bb57882ef318 | LubosKolouch/hackerrank | /regex/identifying_comments.py | 545 | 3.5 | 4 | #!/bin/env python
""" https://www.hackerrank.com/challenges/ide-identifying-comments/problem """
import fileinput
import re
output = ''
in_comment = 0
for line in fileinput.input():
pattern = r'(\/\/.*)'
x = re.findall(pattern, line)
if x:
output += x[0]
output += "\n"
if in_comment or re.search(r'\/\*', line):
in_comment = 1
if in_comment:
output += re.findall(r'(?:\s*)(.*)', line)[0]
output += "\n"
if re.search(r'\*\/', line):
in_comment = 0
print(output)
|
187e6ed4174089c1e90daa2791882cb2cbbbcf89 | guilhemelias/SemGrids-Maker | /SemGridsMakerPyQt/view/manager.py | 3,312 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 10:23:54 2021
@author: gelias
"""
from maker import Maker
from arduino import Arduino
class Manager():
"""
Manager of the model. It is called by the view. It makes the link between the model and the view
"""
def __init__(self):
"""
The cinstructor zhich instanciate the maker and the arduino part
"""
self.maker = Maker()
self.arduino =Arduino()
self.myCurrentGrid=None
def addSemGrid(self,name,seq,desc):
"""
A fonction to add a Grid to the model
"""
for grid in self.maker.mesSemGrids:
if (grid.name == name):
return False
self.maker.addSemGrids(name,seq,desc)
def deleteSemGrid(self,name):
"""
A fonction to delete a Grid to the model
"""
grid=self.searchSemGrids(name)
index = self.maker.mesSemGrids.index(grid)
self.maker.deleteSemGrid(index)
def searchSemGrids(self,name):
"""
A fonction to search a Grid to the list of saved grid
"""
for grid in self.maker.mesSemGrids:
print(grid.name)
if (grid.name == name):
return grid
return False
def getStepFromGrid(self,grid):
"""
A fonction to get the steps from a grid
"""
tabStep = []
for step in grid.sequence:
tabStep.append(step[0])
return tabStep
def getLapFromGrid(self,grid):
"""
A fonction to get the laps from a grid
"""
tabLaps = []
for step in grid.sequence:
tabLaps.append(step[1])
return tabLaps
def setCurrentGrid(self,grid):
"""
A fonction to set the current grid
"""
self.myCurrentGrid=grid
def getMyCurrentGrid(self):
"""
A fonction to get the current grid, to get his informations
"""
return self.myCurrentGrid
def connectArduino(self):
"""
A fonction to connect to arduino using the port COM
"""
portCom=self.maker.get_portCom()
self.arduino.connect(portCom)
def sendDataPatternArduino(self,gap,index,tab1,tab2):
"""
A fonction to send data to arduino for running programm
"""
chain = "pattern"
chain = chain+'/'+str(index)
chain = chain+'/'+str(gap)
for elem in tab1:
chain = chain+'/'+str(elem)
for elem in tab2:
chain = chain+'/'+str(elem)
self.arduino.sendValue(chain)
def sendDataCCWArduino(self,gap,direction):
"""
A fonction to send data to arduino for running programm
"""
chain = "cw"
chain = chain+'/'+direction
chain = chain+'/'+str(gap)
self.arduino.sendValue(chain)
def receiveValueArduino(self):
"""
A fonction to recive data from arduino
"""
self.arduino.receivevalue()
def closeArduino(self):
"""
A fonction to discconnect from arduino
"""
self.arduino.close()
|
8c8861259b03ed4f89574f56a3fff922b05619fa | drazovicfilip/Firecode | /Problems/firecode4_fibonacci.py | 1,182 | 4.1875 | 4 | """ The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it.
Write a recursive method fib(n) that returns the nth Fibonacci number. n is 0 indexed, which means that in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..., n == 0 should return 0 and n == 3 should return 2.
Assume n is less than 15.
Even though this problem asks you to use recursion, more efficient ways to solve it include using an Array, or better still using 3 volatile variables to keep a track of all required values. Check out this blog post to examine better solutions for this problem.
Examples:
fib(0) ==> 0
fib(1) ==> 1
fib(3) ==> 2 """
def fib(n):
# Edge cases
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
elif n == 3:
return 2
previous1 = 1
previous2 = 1
current = previous1 + previous2
# Traverse through the fibonacci sequence, updating it for the needed amount of times
for i in range(3, n):
previous1 = previous2
previous2 = current
current = previous1 + previous2
return current |
9cfba274c8e6c45c76f5571b58fe3d94379e3175 | drazovicfilip/Firecode | /Problems/firecode3_verticalFlip.py | 646 | 4.03125 | 4 | """ You are given an m x n 2D image matrix (List of Lists) where each integer represents a pixel. Flip it in-place along its vertical axis.
Example:
Input image :
1 0
1 0
Modified to :
0 1
0 1 """
def flip_vertical_axis(matrix):
rows = len(matrix)
cols = len(matrix[0])
# Traverse all rows
for col in range(0, int(cols/2)):
# Traverse all columns
for row in range(0, rows):
# Flip vertically mirrored indexes
temp = matrix[row][col]
matrix[row][col] = matrix[row][cols-1-col]
matrix[row][cols-1-col] = temp |
9698999adb69ef7acbd3155bcfa773c0c8ca775d | amingilani/adventofcode2020 | /2/solution.py | 1,375 | 3.515625 | 4 | import re
import os, sys
data = [line.strip() for line in open(os.path.join(sys.path[0], "input.txt"), "r")]
solution = open(os.path.join(sys.path[0], "solution.txt"), "w")
# Part 1
count = 0
for line in data:
(left_half, right_half) = line.split(":")
(lower_limit, upper_limit) = left_half[0:-2].split("-")
character = left_half[-1]
password = right_half.strip()
char_count = password.count(character)
if char_count <= int(upper_limit) and char_count >= int(lower_limit):
count += 1
print(f"The answer to the first part is {count}")
solution.write(f"The answer to part 1 is {count}")
# Part 2
count_2 = 0
for line in data:
(left_half, right_half) = line.split(":")
(first_index, second_index) = left_half[0:-2].split("-")
character = left_half[-1]
password = right_half.strip()
# this is super ugly code, but only one of the positions can have the character
# please don't judge me, I just want the answer
if (password[int(first_index) - 1] == character) and (
password[int(second_index) - 1] == character
):
continue
if (password[int(first_index) - 1] == character) or (
password[int(second_index) - 1] == character
):
count_2 += 1
print(f"The answer to the second part is {count_2}")
solution.write(f"The answer to part 2 is {count_2}")
solution.close() |
34cb4ffeefb8d79f69b9096c894cfcb0980ad060 | LzWaiting/02.PythonNet | /code/tcp_example.py | 803 | 3.53125 | 4 | '''服务端'''
from socket import *
# 1. 创建套接字
sockfd = socket(AF_INET,SOCK_STREAM)
# 2. 绑定服务端地址
sockfd.bind('0.0.0.0',8888)
# 3. 设置监听套接字,创建监听列队
sockfd.listen(5)
# 4. 等待处理客户端连接请求
connfd,addr = sockfd.accept() # connfd 客户端连接套接字,addr 客户端地址
# 5. 收接发数据
data = connfd.recv(1024)
n = connfd.send(b'相应回复信息')
# 6. 关闭套接字
connfd.close()
sockfd.close()
'''客户端'''
# 1. 创建客户端套接字
sockfd = socket(AF_INET,SOCK_STREAM)
# 2. 连接服务端地址
server_addr = ('127.0.0.1',8888)
sockfd.connect(server_addr)
# 3. 接收发数据
data = input('发送>>')
sockfd.send(data.encode())
data = sockfd.recv(1024).decode()
# 4. 关闭套接字
sockfd.close() |
65c21678d5253dcb9b07c42566ac525c42100d4f | DiegoMeruoca/Python-1-Primeiros-Comandos | /Desafio 3.py | 419 | 3.84375 | 4 | # Desafio 3 - Desconto do produto
preco = float(input("Digite um valor do produto:")) # Recebe o valor e converte para float
percDesc = float(input("Digite a porcentagem de desconto(Apenas números):")) # Recebe o valor e converte para float
desconto = preco*percDesc/100
novoPreco = preco - desconto
print("O desconto é de {:.2f} e o preço com desconto é R$ {:.2f}!!! "
.format(desconto, novoPreco))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.