blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
423efa88a1f82048f7ca53999a5afb695a946a49 | Luciferochka/Colokvium | /19.py | 616 | 3.953125 | 4 | #Знайти суму всіх елементів масиву цілих чисел що задовольняють умові: остача від ділення на 2 дорівнює 3. Розмірність масиву - 20. Заповнення масиву здійснити випадковими числами від 200 до 300.
import numpy as np
import random
n = 20
a = np.zeros((n),dtype=int)
sum = 0
for i in range(n):
a[i] = random.randint(200,300)
if a[i]%2 == 3:
sum += a[i]
print(f'Your arr:{a}')
if sum == 0:
print('You have no sum')
else:
print(f'Your sum:{sum}') |
9b8e57889bb7379646823306c183ee29b2295288 | fanser123/The-courseware | /day7/d5.py | 247 | 3.59375 | 4 | #-*-coding:utf-8 -*-
#!/usr/bin/python3
# @Author:liulang
'''
可变对象,调用函数的时候,传地址,不可变,传值
'''
def change_list(list1):
list1.append("1")
test_data = [1,2,3]
change_list(test_data)
print(test_data)
|
8dbaa03ffa9bf8ff6892278be38e5bd2175f95e0 | rauladolfotecgda/Python-Exercises | /WSQ12 - Word counter.py | 292 | 3.671875 | 4 | #Raúl Adolfo Torres Vargas
#A01400187
#WSQ12
fs= "We have flowers and flowersflowers. Four FlOwErs in fact "
count= 0
fs = fs.lower()
w= "FlOwErs"
w= w.lower()
lf = fs.find(w)
while(lf >= 0):
print("Found flower at ", lf)
count = count + 1
lf = fs.find(w, lf + 1)
print("I found ", count,"of", w) |
733ac4b00990994a2c9d0b3458fd817eaa0a4e32 | AlexeySergeychuk/AlexeySergeychukPython | /testt.py | 1,250 | 3.59375 | 4 | class Sklad:
list = []
@staticmethod
def counts():
print(f'На складе содержится следующая продукция: {Sklad.list}')
class Equipment:
def __init__(self, mark, name, year):
self.mark = mark
self.name = name
self.year = year
def addsklad(self):
return Sklad.list.append([self.mark, self.name, self.year])
@property
def year(self):
return self.year
@year.setter
def year(self, year):
if self.year > 2021:
self.year = 2021
else:
self.year = year
class Printer(Equipment):
def __init__(self, mark, name, year, color):
super().__init__(mark, name, year)
self.color = color
class Scaner(Equipment):
def __init__(self, mark, name, year, ip):
super().__init__(mark, name, year)
self.ip = ip
class Xerox(Equipment):
def __init__(self, mark, name, year, someperk):
super().__init__(mark, name, year)
self.someperk = someperk
lasers = Printer('lasers', 'l2', 2025, 'red')
lasers.addsklad()
somexerox = Xerox('Xerox', 'R300', 2019, 'best Xerox')
somexerox.addsklad()
Sklad.counts()
|
d94e0125e48f4b71c5df363da5e76673e9129f15 | Roshan84ya/data-structure-with-python | /segmenttree/segment_tree sum update.py | 3,118 | 3.71875 | 4 | #building the segmenttree for the given array
"""
for building the segment tree we need to build the tree till we reach at the base condition that is when end ==start i.e the case when in out segment tree has only one element and that is
equal to the element at index i so in this manner we are firstly filling the element at the last index i.e from last to first
and if the index of parent node is =i then the index of its right node is 2*i and the index of its left node is 2*i +1
so we build the segmrnt tree y the recursive call we firsty find out the mid element
mid=(end+start)/2 and our left subtree will indicatr the element from start to mid and its index will be (2*i-->indexof parent node)
similarly for the right subtree will indicate the element from the mid+1 to the end and it sindex will be 2*index +1
"""
def buildtree(arr,s,end,index):
if s==end:
tree[index]=arr[s]
else:
mid=(s+end)//2
buildtree(arr,s,mid,2*index)
buildtree(arr,mid+1,end,2*index+1)
tree[index]=tree[2*index]+tree[2*index +1]
#get sum in the range of a,b
"""
here we have three cases i.e if some element is partially inside the range of a,b then we break the element nto more smaller and we return the value when the give range is totally inside
our range of a,b i.e a<=s<=end<=b
if some element is not in the rrange of a,b i.e totally out of the range of the ab then we will just return 0 as we are not interested in finding the sum of that element
the condition for that is
if s>b(end of fired query) or a >end(end of our subarray)
"""
def getsum(a,b,s,end,index):
if s>b or a>end:
return 0
elif a<=s and b>=end:
return tree[index]
mid=(s+end)//2
return getsum(a,b,s,mid,2*index)+getsum(a,b,mid+1,end,2*index +1)
#updating value
"""
we update al the value that will fall in in which our uppdating index will fall i.e s<=i<=b
and if our index willl not fall in the range then we simply return
and we call our recursive function till we reach at the leaf node i.e till we have 1 element in the leaf node
"""
def update(s,end,upidx,diff,index):
if end<upidx or s>upidx:
return
if s<=upidx<=end:
tree[index]+=diff
if end>s:
mid=(s+end)//2
update(s,mid,upidx,diff,2*index)
update(mid+1 ,end,upidx,diff,2*index +1)
arr=[10,20,30,40] #arr for which we need to build the segment tree
tree=[0]*4*(len(arr))
#building the segment tree
buildtree(arr,0,len(arr)-1,1)
print(*tree)
#getsum range query
a,b=map(int,input().split())
print(getsum(a,b,0,len(arr)-1,1))
#update tree
uindex,value=map(int,input().split())
update(0 , len(arr)-1 ,uindex ,value-arr[uindex],1)
print(*tree)
#update tree
uindex,value=map(int,input().split())
update(0 , len(arr)-1 ,uindex ,value-arr[uindex],1)
print(*tree)
#getsum range query
a,b=map(int,input().split())
print(getsum(a,b,0,len(arr)-1,1))
#getsum range query
a,b=map(int,input().split())
print(getsum(a,b,0,len(arr)-1,1))
|
27dfa83501276d2594a82baa702753f448a2530c | jotanice/JDev | /Python/GGuanabara/ex3.py | 162 | 3.890625 | 4 | # -*- coding: utf-8 -*-
n1 = input('Digite um número: ')
n2 = input('Digite outro número: ')
#n11 = int(n1)
#n21 = int(n2)
print('A soma é ',int(n1)+int(n2)) |
7d60bd6fda2d94da3cebbf66d07b9564591dd089 | rajputarun/machine_learning_intern | /keras_bottleneck_multiclass.py | 6,828 | 3.578125 | 4 | '''
Using Bottleneck Features for Multi-Class Classification in Keras
We use this technique to build powerful (high accuracy without overfitting) Image Classification systems with small
amount of training data.
The full tutorial to get this code working can be found at the "Codes of Interest" Blog at the following link,
http://www.codesofinterest.com/2017/08/bottleneck-features-multi-class-classification-keras.html
Please go through the tutorial before attempting to run this code, as it explains how to setup your training data.
The code was tested on Python 3.5, with the following library versions,
Keras 2.0.6
TensorFlow 1.2.1
OpenCV 3.2.0
This should work with Theano as well, but untested.
'''
import numpy as np
import pandas as pd
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D, GlobalAveragePooling2D
from keras import applications
from keras import optimizers
from keras import regularizers
from keras.layers.normalization import BatchNormalization
from keras.utils.np_utils import to_categorical
import matplotlib.pyplot as plt
import math
import cv2
# dimensions of our images.
img_width, img_height = 224, 224
top_model_weights_path = 'bottleneck_fc_model.h5'
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
# number of epochs to train top model
epochs = 50
# batch size used by flow_from_directory and predict_generator
batch_size = 16
#######################################################################
def save_bottlebeck_features():
# build the VGG16 network
model = applications.VGG16(include_top=False, weights='imagenet')
datagen = ImageDataGenerator(rescale=1. / 255)
generator = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None,
shuffle=False)
print(len(generator.filenames))
print(generator.class_indices)
print(len(generator.class_indices))
nb_train_samples = len(generator.filenames)
num_classes = len(generator.class_indices)
predict_size_train = int(math.ceil(nb_train_samples / batch_size))
bottleneck_features_train = model.predict_generator(
generator, predict_size_train)
np.save('bottleneck_features_train.npy', bottleneck_features_train)
generator = datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None,
shuffle=False)
nb_validation_samples = len(generator.filenames)
predict_size_validation = int(
math.ceil(nb_validation_samples / batch_size))
bottleneck_features_validation = model.predict_generator(
generator, predict_size_validation)
np.save('bottleneck_features_validation.npy',
bottleneck_features_validation)
save_bottlebeck_features()
#######################################################################
def train_top_model():
datagen_top = ImageDataGenerator(rescale=1. / 255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
generator_top = datagen_top.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
shuffle=False)
nb_train_samples = len(generator_top.filenames)
num_classes = len(generator_top.class_indices)
# save the class indices to use use later in predictions
np.save('class_indices.npy', generator_top.class_indices)
# load the bottleneck features saved earlier
train_data = np.load('bottleneck_features_train.npy')
# get the class lebels for the training data, in the original order
train_labels = generator_top.classes
# https://github.com/fchollet/keras/issues/3467
# convert the training labels to categorical vectors
train_labels = to_categorical(train_labels, num_classes=num_classes)
generator_top = datagen_top.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None,
shuffle=False)
nb_validation_samples = len(generator_top.filenames)
validation_data = np.load('bottleneck_features_validation.npy')
validation_labels = generator_top.classes
validation_labels = to_categorical(
validation_labels, num_classes=num_classes)
model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(num_classes, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy', metrics=['accuracy'])
# history = model.fit(train_data, train_labels,
# epochs=epochs,
# batch_size=batch_size,
# validation_data=(validation_data, validation_labels))
history = model.fit_generator(datagen_top.flow(train_data, train_labels, batch_size=batch_size),
steps_per_epoch=int(np.ceil(train_data.shape[0] / float(batch_size))),
epochs=epochs,
validation_data=(validation_data, validation_labels),
workers=4)
model.save_weights(top_model_weights_path)
(eval_loss, eval_accuracy) = model.evaluate(
validation_data, validation_labels, batch_size=batch_size, verbose=1)
print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100))
print("[INFO] Loss: {}".format(eval_loss))
plt.figure(1)
# summarize history for accuracy
plt.subplot(211)
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
# summarize history for loss
plt.subplot(212)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
train_top_model()
####################################################################### |
fda771a7d5f235a09c8d526714626c9e2e06fc1e | cosmosZhou/sympy | /axiom/algebra/lt/lt/imply/lt/abs/mul.py | 531 | 3.65625 | 4 | from util import *
@apply
def apply(x_less_than_a, y_less_than_b):
abs_x, a = x_less_than_a.of(Less)
abs_y, b = y_less_than_b.of(Less)
x = abs_x.of(Abs)
y = abs_y.of(Abs)
return Less(abs(x * y), a * b)
@prove
def prove(Eq):
from axiom import algebra
x, y, a, b = Symbol(real=True)
Eq << apply(abs(x) < a, abs(y) < b)
Eq << algebra.lt.lt.imply.lt.mul.apply(Eq[0], Eq[1])
Eq << Eq[-1].this.lhs.apply(algebra.mul.to.abs)
if __name__ == '__main__':
run()
# created on 2020-01-07
|
3da216050ff4d76013231ef9477a1ddddae9f853 | TardC/books | /Python编程:从入门到实践/code/chapter-11/test_employee.py | 673 | 3.609375 | 4 | import unittest
from employee import Employee
class EmployeeTestCase(unittest.TestCase):
"""Test Employee.py"""
def setUp(self):
"""Create a Employee object."""
self.my_employee = Employee('tard', 'c', 150000)
def test_give_default_raise(self):
"""Test the default arguement will work well."""
self.my_employee.give_raise()
self.assertEqual(155000, self.my_employee.year_salary)
def test_give_custom_raise(self):
"""Test a custom arguement will work well."""
self.my_employee.give_raise(20000)
self.assertEqual(170000, self.my_employee.year_salary)
unittest.main()
|
cf9aebff417467535b257489bd2329121a467800 | Israelgd85/Pycharm | /excript/app-comerciais-kivy/Python(Udemy-Claudio Rogerio/Exe_lista_4/exe-4.py | 353 | 3.8125 | 4 | # 4) Escreva um algoritmo contendo uma função que necessite de três argumentos.
# Em seguida, imprima na tela os argumentos em ordem ascendente e,
# por fim, imprima a média aritmética:
arg = [23,13,12]
def ascendente (x,y,z):
media = (x + y + z) / 3
print(arg)
print("A média caculada é :", media)
arg.sort()
ascendente(*arg)
|
193876b6601a74e75efe0e12241dcf1ee61cd0e1 | muhsayd/panenthe | /shared/drivers/attrdict.py | 2,868 | 3.609375 | 4 | #!/usr/bin/env python
# Panenthe: attrdict.py
# Defines a class that converts a dictionary input into attributes
##
class attrdict(object):
def __init__(self, dict):
for attr in dict:
exec("self.%s = dict[attr]" % attr)
self.dict = dict
# return dict
def get_dict(self):
return self.dict
# require attributes
def require(self, requirements):
if isinstance(requirements, str):
try:
eval("self.%s" % requirements)
except AttributeError:
return False
return True
else:
for i in requirements:
try:
eval("self.%s" % i)
except AttributeError:
return False
return True
# require dictionary keys
def require_dict(self, dict, requirements):
if isinstance(requirements, str):
try:
eval("dict[\"%s\"]" % requirements)
except KeyError:
return False
return True
else:
for i in requirements:
try:
eval("dict[\"%s\"]" % i)
except KeyError:
return False
return True
# force casting as integer
def force_cast_int(self, castees):
return self.force_cast_type(int, castees)
def force_cast_int_dict(self, dictnames, castees):
return self.force_cast_type_dict(int, dictnames, castees)
# force casting as boolean
def force_cast_bool(self, castees):
return self.force_cast_type(bool, castees)
def force_cast_bool_dict(self, dictnames, castees):
return self.force_cast_type_dict(bool, dictnames, castees)
# force casting as a type
def force_cast_type(self, vartype, castees):
if isinstance(castees, str):
exec("self.%s = vartype(self.%s)" % (castees, castees))
exec("self.dict[\"%s\"] = self.%s" % (castees, castees))
else:
for i in castees:
exec("self.%s = vartype(self.%s)" % (i, i))
exec("self.dict[\"%s\"] = self.%s" % (i, i))
# force casting as a type on dictionary
def force_cast_type_dict(self, vartype, dictnames, castees):
# parse dictname if list
# ["a", "b", "c"] produces the following string for dictobjectname:
# a["b"]["c"]
# and for dictname:
# a"]["b"]["c
if isinstance(dictnames, list):
dictname = "\"][\"".join(dictnames)
dictobjectname = \
dictnames[0] + "[\"" + "\"][\"".join(dictnames[1:]) + "\"]"
# not a list, just a string
else:
dictname = dictnames
dictobjectname = dictnames
# deal with casting for a single item
if isinstance(castees, str):
exec("self.%s[\"%s\"] = vartype(self.%s[\"%s\"])" % (
dictobjectname, castees,
dictobjectname, castees
))
exec("self.dict[\"%s\"][\"%s\"] = self.%s[\"%s\"]" % (
dictname, castees,
dictobjectname, castees
))
# deal with casting for multiple items
else:
for i in castees:
exec("self.%s[\"%s\"] = vartype(self.%s[\"%s\"])" % (
dictobjectname, i,
dictobjectname, i
))
exec("self.dict[\"%s\"][\"%s\"] = self.%s[\"%s\"]" % (
dictname, i,
dictobjectname, i
))
|
8223fc48bc510ee049bebfa52d36df4fa4475290 | Elanakova/python-programming-stepik | /total_sleep.py | 194 | 3.71875 | 4 | #Tim sleeps X hours at night and Y minutes in the afternoon.
#Count how many minutes Tim sleeps per day.
#Input:
#7
#30
#Output:
#450
X = int(input())
Y = int(input())
print(X*60 + Y) |
8d782f3d4b9fdd9c85c7cdb83d0f1db01feb2a3d | crl0636/Python | /code/Search2DMatrix.py | 683 | 3.609375 | 4 | class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
start = 0
end = len(matrix) - 1
while start <= end:
mid = (start + end) // 2
if target in matrix[mid]:
return True
else:
if len(matrix[mid]) != 0 and matrix[mid][0] > target:
end -= 1
else:
start += 1
return False
if __name__ == '__main__':
so = Solution()
so.searchMatrix(
[[1]], 1) |
0bb1e6666940e5b3c715b333b20986a732e859f2 | hrishitelang/Python-For-Everybody | /Programming for Everybody (Getting Started with Python)/Week 6/Assignment4.6.py | 230 | 3.8125 | 4 | def computepay(h,r):
if h<=40:
return h*r
elif h>40:
return (h*r + (h-40)*0.5*r)
hrs = float(input("Enter Hours:"))
rph = float(input("Enter Rate per hour:"))
p = computepay(hrs,rph)
print("Pay",p)
|
f828fe9d26ba2e7be02793d901da603ceb96475c | JianxiangWang/LeetCode | /6 ZigZag Conversion/solution.py | 624 | 3.6875 | 4 | #!/usr/bin/env python
#encoding: utf-8
import sys
import operator
reload(sys)
sys.setdefaultencoding('utf-8')
class Solution(object):
def convert(self, s, numRows):
if numRows < 2 or numRows >= len(s):
return s
zigzag = [[] for _ in range(numRows)]
row, step = 0, 1
for c in s:
zigzag[row] += c
if row == 0:
step = 1
if row == numRows - 1:
step = -1
row += step
return "".join(map(lambda x: "".join(x), zigzag))
if __name__ == '__main__':
print Solution().convert("", 1)
|
4d2973e2c6894654773a9da9985625dbaf9ad81f | xinxinboss/PythonDemo | /oop_demo/test02.py | 743 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-30 11:26:38
# @Author : TaoYuan ([email protected])
# @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408
# @Version : $Id$
# 继承和多态
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def dog_run(self):
print('Dog is running...')
# 子类可以继承父类的所有功能
dog = Dog()
dog.run()
dog.dog_run()
print('-' * 30)
a = list()
b = Animal()
c = Dog()
print(isinstance(a, list))
print(isinstance(b, Animal))
print(isinstance(c, Dog))
# 上述没错,但是c同时也可以是Animal
print(isinstance(c, Animal))
# 获取该对象所有的属性和方法
print(dir(Dog()))
|
60862d8b0787ffa6e257df54ae25189befa09927 | RizaZNisa/basic-python-b4-c | /Day 2/input.py | 544 | 4.21875 | 4 | #That means we are able to ask the user for input as a STRING.
# cara 1
name = input("Masukkan nama kamu : ")
umur = input("Masukkan umur kamu : ")
#perlu spasi jika menggunakan + dan hanya untuk type data STRING
print("Nama saya adalah " + name + " sedangkan umur saya adalah " + umur + " tahun")
# tidak perlu spasi jika menggunakan ,
#print("Nama saya adalah" ,name, "sedangkan umur saya adalah" ,umur, "tahun"))
# cara 2
print("Nama : "+name)
print("Umur : "+umur)
# type data
print(type(name))
print(type(umur))
|
d46a7ef37dd2b009606bfb88ea08be9919a6ebf9 | davidknoppers/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 226 | 3.5 | 4 | #!/usr/bin/python3
def new_in_list(mylist, idx, element):
if mylist is None:
return (None)
copy = mylist[:]
if idx < 0 or idx >= len(copy):
return (mylist)
copy[idx] = element
return (copy)
|
53e6c367c4828e9dbd5ebbce4720ba2b0c24ee13 | sreyansb/Python_Mini_Compiler | /FINAL/Code_Optimization/dead_code_elimination.py | 1,598 | 3.53125 | 4 | '''
Code logic:
Loop through all the lines in the quads (i.e. while flag is True) at every iteration and for
every such line-see if there is no line where the result of the first line is used.
'''
import csv
import copy
PATH_TO_CSV = r"./non_optimized/show.tsv"
PATH_TO_OUTPUT_1 = r"./optimized/showDCE.tsv"
file_input = open(PATH_TO_CSV)
quads = list(csv.reader(file_input, delimiter='\t'))
#print(quad)
def dead_code_elimination(quads):
flag = True
remove = True
while(flag):
flag = False
for i in range(len(quads)):
remove = True
if(quads[i][4] != "-" and quads[i][1].lower() not in ["label", "goto", "if false", "if"]):
for j in range(len(quads)):
if((quads[i][4] == quads[j][2] and quads[j][0] != "-1") or (quads[i][4] == quads[j][3] and quads[j][0] != "-1")):
remove = False
if((remove == True) and (quads[i][0] != "-1")):
#print(i+1)
quads[i][0] = "-1"
flag = True
return quads
quads_copy = copy.deepcopy(quads)
quads_output_1 = dead_code_elimination(quads_copy[1:])
quads_output_1.insert(0, quads[0])
quads_output_1=[i for i in quads_output_1 if i[0]!='-1']
index=1
for i in range(1,len(quads_output_1)):
quads_output_1[i][0]=str(index)
index+=1
#print(quads_output_1)
file_output = open(PATH_TO_OUTPUT_1, "w")
csv_writer = csv.writer(file_output, delimiter='\t', lineterminator = "\n")
csv_writer.writerows(quads_output_1)
file_output.flush()
file_output.close()
file_input.close()
|
08390f2e175b2a457f6238ee0d373648260a0faa | suvgerlop142/Ch.03_Input_Output | /pratice.py | 205 | 4.21875 | 4 | print("WELCOME, to the MPG calculator\n")
miles=float(input("Please enter miles traveled: "))
gal=float(input("How many gallons of gas did you use: "))
mpg=miles/gal
print("Your gas mileage is",mpg,"mpg")
|
856e9a12c6d4e0866b164b67448332687e529640 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/9023a422b83f4d26a7d57e154eb8afbb.py | 462 | 4 | 4 | def sum_of_squares(number,summation = 0):
if number == 0:
return summation
else:
summation += number**2
return sum_of_squares(number-1,summation)
def square_of_sum(number, summation = 0):
if number == 0:
return summation**2
else:
summation += number
return square_of_sum(number-1,summation)
def difference(number):
return square_of_sum(number) - sum_of_squares(number)
|
5bc2bfc9d39478a8ed23a914b2562e11f101f7fa | MegaMotion/SVR_Blender_Automation_Plugin | /fake_bpy_modules_2.82-20200514/bpy/utils/units.py | 2,150 | 4.0625 | 4 | import sys
import typing
def to_string(unit_system: str,
unit_category: str,
value: float,
precision: int = 3,
split_unit: bool = False,
compatible_unit: bool = False) -> str:
'''Convert a given input float value into a string with units.
:param unit_system: The unit system, from bpy.utils.units.systems.
:type unit_system: str
:param unit_category: The category of data we are converting (length, area, rotation, etc.), from bpy.utils.units.categories.
:type unit_category: str
:param value: The value to convert to a string.
:type value: float
:param precision: Number of digits after the comma.
:type precision: int
:param split_unit: Whether to use several units if needed (1m1cm), or always only one (1.01m).
:type split_unit: bool
:param compatible_unit: Whether to use keyboard-friendly units (1m2) or nicer utf-8 ones (1m²).
:type compatible_unit: bool
:return: The converted string.
'''
pass
def to_value(unit_system: str,
unit_category: str,
str_input: str,
str_ref_unit: str = None) -> float:
'''Convert a given input string into a float value.
:param unit_system: The unit system, from bpy.utils.units.systems.
:type unit_system: str
:param unit_category: The category of data we are converting (length, area, rotation, etc.), from bpy.utils.units.categories.
:type unit_category: str
:param str_input: The string to convert to a float value.
:type str_input: str
:param str_ref_unit: A reference string from which to extract a default unit, if none is found in str_input.
:type str_ref_unit: str
:return: The converted/interpreted value.
'''
pass
categories = None
'''constant value bpy.utils.units.categories(NONE=NONE, LENGTH=LENGTH, AREA=AREA, VOLUME=VOLUME, MASS=MASS, ROTATION=ROTATION, TIME=TIME, VELOCITY=VELOCITY, ACCELERATION=ACCELERATION, CAMERA=CAMERA, POWER=POWER) '''
systems = None
'''constant value bpy.utils.units.systems(NONE=NONE, METRIC=METRIC, IMPERIAL=IMPERIAL) '''
|
98d5ea2964946106a5ce430c4e7e30ba75d4461b | nvincenthill/python-sandbox | /loops.py | 272 | 3.890625 | 4 | knights = {'gallahad': 'the pure', 'robin': 'the brave'}
# use items() to access each key/value pair in dictionary
for k, v in knights.items():
print(k, v)
# enumerate over list to access each value/index
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
|
d4345ce95afd2b4d1a54f00a43a75af49197de0d | MartinLesser/Procedural-distribution-of-vegetation | /intern/src/python/Gui/new_vegetation_type_window.py | 2,982 | 3.734375 | 4 | import tkinter as tk
from intern.src.python.Data.vegetation import Vegetation
from intern.src.python.Gui.vegetation_window import VegetationWindow
class NewVegetationWindow(tk.Frame):
"""
Window for creating new vegetation.
"""
def __init__(self, parent, main_window, controller):
tk.Frame.__init__(self, parent)
self.main_window = main_window
self.controller = controller
row = 0
column = 0
tk.Button(self, text="< Back to vegetation types",
command=lambda: main_window.show_frame("VegetationWindow")).grid(row=row, column=column, pady=10)
row += 1
tk.Label(self, text="New vegetation type:", font='Helvetica 16 bold').grid(row=row, column=column, pady=10)
height = 1
width = 10
column += 1
row += 1
tk.Label(self, text="Name:").grid(row=row, column=column, pady=10)
self.new_vegetation_name = tk.Text(self, height=height, width=width)
self.new_vegetation_name.grid(row=row, column=column + 1, pady=10)
row += 1
tk.Label(self, text="Energy demand (in kcal/day):").grid(row=row, column=column, pady=10)
self.new_vegetation_energy_demand = tk.Text(self, height=height, width=width)
self.new_vegetation_energy_demand.grid(row=row, column=column + 1, pady=10)
row += 1
tk.Label(self, text="Water demand (in l/cm²):").grid(row=row, column=column, pady=10)
self.new_vegetation_water_demand = tk.Text(self, height=height, width=width)
self.new_vegetation_water_demand.grid(row=row, column=column + 1, pady=10)
row += 1
tk.Label(self, text="Soil demand:").grid(row=row, column=column, pady=10)
self.soil_demand = tk.ttk.Combobox(self, values=[soil.name for soil in self.controller.soils.values()])
self.soil_demand.grid(row=row, column=column + 1, pady=10)
row += 1
tk.Label(self, text="Soil depth demand (in cm):").grid(row=row, column=column, pady=10)
self.new_vegetation_soil_depth_demand = tk.Text(self, height=height, width=width)
self.new_vegetation_soil_depth_demand.grid(row=row, column=column + 1, pady=10)
row += 1
tk.Button(self, text="Save vegetation",
command=lambda: self.save_vegetation()).grid(row=row, column=column, pady=10)
def save_vegetation(self):
name = self.new_vegetation_name.get("1.0", 'end-1c')
energy_demand = self.new_vegetation_energy_demand.get("1.0", 'end-1c')
water_demand = self.new_vegetation_water_demand.get("1.0", 'end-1c')
soil_demand = self.soil_demand.get()
soil_depth_demand = self.new_vegetation_soil_depth_demand.get("1.0", 'end-1c')
new_vegetation = Vegetation(name, energy_demand, water_demand, soil_demand, soil_depth_demand)
new_vegetation.save_vegetation()
self.controller.load_vegetations()
self.main_window.update_frame(VegetationWindow)
|
7d92cba565129f9d0c9433aa7b7311c26d2b40cc | sanjay1313/Python-practice | /list_tuple.py | 216 | 4.21875 | 4 | def change_string(string):
list1 = string.split(',')
tuple1 = tuple(list1)
print("List : ",list1)
print("Tuple : ",tuple1)
string = input("Enter numbers separated by comma : ")
change_string(string) |
7d738f2fcc3aad537338dfe6f40b4b999c001617 | vibhubhatia007/AllAboutML | /MultipleLinearRegression/Multiple_linear_regression2.py | 1,766 | 3.5625 | 4 | #import the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
#encoding the catgorical values into discreet values
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X= LabelEncoder()
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()
#avoiding the dummy variable trap
X = X[:, 1:]
#splitting the data into training and test sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2, random_state = 0)
#fitting multiple linear rehression to the training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#predicting the test set result
y_pred = regressor.predict(X_test)
#building the optimal model uusing backward elemination
import statsmodels.formula.api as sm
#X = np.append(arr =X , values = np.ones((50,1)).astype(int), axis =1)
X = np.append(arr = np.ones((50,1)).astype(int), values = X, axis =1)
X_opt = X[:, [0,1,2,3,4,5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0,1,3,4,5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0,3,4,5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0,3,5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0,3]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
|
c08f9d023b6116f2f899ab1a935b8504ecfeaf90 | adrian-calugaru/fullonpython | /classes.py | 1,894 | 3.6875 | 4 | import random
class Vehicle:
def __init__(self, make, model, year, weight, needsMaintenance = False, tripsSinceMaintenance = 0):
self.make = make
self.model = model
self.year = year
self.weight = weight
self.needsMaintenance = needsMaintenance
self.tripsSinceMaintenance = tripsSinceMaintenance
def getMake(self):
return self.make
def getModel(self):
return self.model
def getYear(self):
return self.year
def getWeight(self):
return self.weight
def repair(self):
self.tripsSinceMaintenance = 0
self.needsMaintenance = False
class Cars(Vehicle):
def __init__(self, make, model, year, weight, isDriving = False):
Vehicle.__init__(self, make, model, year, weight)
self.isDriving = isDriving
def drive(self):
self.isDriving = True
def stop(self):
if self.isDriving:
self.tripsSinceMaintenance += 1
if self.tripsSinceMaintenance > 100:
self.needsMaintenance = True
self.isDriving = False
def randomly_drive_car(car):
drive_times = random.randint(1, 101)
for i in range(drive_times):
car.drive()
car.stop()
def print_car_specs(car):
print('Make ',car.make)
print('Model ',car.model)
print('Year ',car.year)
print('Weight ',car.weight)
print('Needs Maintenance ',car.needsMaintenance)
print('Trips Since Maintenance ',car.tripsSinceMaintenance)
print('Weight ',car.weight)
carOne = Cars("volkswagen group", "ameo", 2010, 1033 )
carTwo = Cars("volkswagen group", "polo", 2008, 1038 )
carThree = Cars("volkswagen group", "vento", 2010, 1023 )
randomly_drive_car(carOne)
randomly_drive_car(carTwo)
randomly_drive_car(carThree)
print_car_specs(carOne)
print_car_specs(carTwo)
print_car_specs(carThree)
|
0a282e473d9b08c8e849efbb3dfe8f4ef616e562 | benwei/Learnings | /pySamples/numbrOperate.py | 303 | 3.609375 | 4 | #!/usr/bin/env python
from decimal import Decimal
## http://stackoverflow.com/questions/4643991/python-converting-string-into-decimal-number
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
result = [float(x.strip(' "')) for x in A1]
print result
result = [Decimal(x.strip(' "')) for x in A1]
print result
|
3d23ba1a4945b36ad43c50c02b00717783cd9f13 | kmlporto/Algoritmo | /Python/Usando vetor e listas/8.py | 847 | 4.09375 | 4 | #pegar todos os estados
estados=[]
for i in range(0,3,1):
nome = input("ESTADO: ")
estados.append(nome)
votos=[]
#pegar todos os votos
v = input("Melhor estado: ")
while (v in estados):
votos.append(v)
v = input("Melhor estado: ")
#variavel para comparar o estado mais votado, e quant de votos que o mais votado
#por enquanto nao existe e a quant de votos é 0
quant_votos = 0
mais_votado = []
for estado in estados:
#a quant de votos seja maior que o mais votado
if votos.count(estado)>quant_votos:
#limpar a lista de mais votado
mais_votado.clear()
#adicionar o nome elemento mais votado
mais_votado.append(estado)
#qnt de votos do mais votado sera novo valor
quant_votos = votos.count(estado)
#caso de empate
elif votos.count(estado)==quant_votos:
mais_votado.append(estado)
print(mais_votado)
|
4253ff097f680765522ef99dfba0a1a4a7453eef | eronekogin/leetcode | /2019/permutations_ii.py | 1,291 | 3.734375 | 4 | """
https://leetcode.com/problems/permutations-ii/
"""
from typing import List
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
"""
Insert to next number to any of the position of the pre permutations.
When the next number is found in the pre permutation, skip the loop on
the current permutation.
For [1, 1], if we want to insert 1, we will insert the new 1 to the
left side of the first 1, thus become [1, 1, 1]. Then skip the
remaining insert positions.
"""
rslt = [[]]
for num in nums:
workRslt = []
for preRslt in rslt:
# Add the current number to the end of the preRslt to
# prevent the not found in the index function. When
# the pre permutation does not contain the current number,
# then it is correct to insert the current number to every
# position of the pre permutation.
validMaxPos = (preRslt + [num]).index(num)
for i in range(validMaxPos + 1):
workRslt.append(preRslt[:i] + [num] + preRslt[i:])
rslt = workRslt
return rslt
nums = [1, 1, 3]
print(Solution().permuteUnique(nums))
|
c90831803ddcce0a3ba05a872d16d0c3f4f15433 | santigp258/MisionTic2022 | /NotasDeClase/problemas.py | 998 | 4.21875 | 4 | '''
Desarrollar un algoritmo que reciba dos cadenas de caracteres y
determine si la primera está incluida en la segunda.
Se dice que una cadena está incluida en otra si todos los caracteres
con repeticiones de la cadena esta en la segunda cadena sin tener en cuenta
el orden de los caracteres.
Ejemplo:
-"prosa" esta incluida en la cadena "la profesora de idiomas"
-"pepito" no esta incluido en "un pedazo de tierra" falta una p
-"pepito" si esta incluido en "tijeras o papel"
'''
'''
Invertir una cadena y decir si es palindroma
'''
cadena = "hola" #aloh
def invertirCadena(palabra) -> str:
invertida = ""
for i in range ((len(palabra)-1),-1,-1):
invertida += palabra[i]
return invertida
def palindromo(palabra):
if invertirCadena(palabra).upper() == palabra.upper():
print(palabra,"Es palindroma")
else:
print(palabra,"No es palindroma")
palindromo("hola")
palindromo("Arepera")
palindromo("Sábado")
palindromo("Amor a Roma")
|
3ad70e93005671ac6a79ede40191f42867ed7655 | CabraKill/transposed_matrix | /src/util/read_var.py | 268 | 3.984375 | 4 | def read_number(text: str, integer: bool = False):
try:
value = float(input("{}".format(text)))
return int(value) if integer else value
except:
print("Insira um número válido!!!")
raise Exception("Insira um número válido!")
|
c2f9baa91ef0468f3d913b189f0ce84bd3a88d76 | fstakem/PMuniX | /src/collectMuniData/Route.py | 1,694 | 3.734375 | 4 | # -----------------------------------------------------------------------------
#
# Route.py
# By: Fred Stakem
# Created: 12.13.11
# Last Modified: 12.13.11
#
# Purpose: This is the route class which is the main class for a bus
# route.
#
# -----------------------------------------------------------------------------
# Import libs
# Import classes
class Route(object):
def __init__(self):
self.name = ''
self.tag = -1
self.stops = []
self.directions = []
self.bounding_box = []
self.paths = []
self.vehicles = []
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
return self.name
def route_to_string(self):
output = self.name + "\n"
output += "Directions: " + "\n"
for direction in self.directions:
output += "\t" + str(direction) + "\n"
output += "Number of paths: " + str(len(self.paths)) + "\n"
output += "Number of vehicles: " + str(len(self.vehicles)) + "\n"
output += "Stops:"
for stop in self.stops:
output += "\t" + str(stop) + "\n"
return output
def vehicles_to_string(self):
output = "Vehicles:" + "\n"
for vehicle in self.vehicles:
output += "\t" + str(vehicle) + "\n"
return output
def stops_to_string(self):
pass
def paths_to_string(self):
pass
|
6cb5520587ef700781ccbdd4f146b15efa27683a | Mostofa-Najmus-Sakib/Applied-Algorithm | /Leetcode/Python Solutions/Linked List/copyListwithRandomPointer.py | 1,650 | 3.515625 | 4 | """
LeetCode Problem: 138. Copy List with Random Pointer
Link: https://leetcode.com/problems/copy-list-with-random-pointer/
Language: Python
Written by: Mostofa Adib Shakib
"""
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head is None:
return head
curr = head
hashmap = {}
while curr:
hashmap[curr] = Node(curr.val)
curr = curr.next
curr = head
while curr:
if curr.next:
hashmap[curr].next = hashmap[curr.next]
if curr.random:
hashmap[curr].random = hashmap[curr.random]
curr = curr.next
return hashmap[head]
# Time Complexity: O(n)
# Space Complexity: O(1)
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return None
curr = head
while curr:
nxt = curr.next
new = Node(curr.val, nxt, None)
new.next = curr.next
curr.next = new
curr = curr.next.next
curr = head
while curr:
if curr.random:
curr.next.random = curr.random.next
curr = curr.next.next
curr = head
nxt = head.next
while curr.next:
temp = curr.next
curr.next = curr.next.next
curr = temp
return nxt |
4ef373e91493f52c1ccb578ff29c48bad7d37a7b | lplade/sea_battle | /player_io.py | 3,431 | 4 | 4 | from constants import *
def msg(string):
"""
This just wraps print()
:param string:
:return:
"""
print(string)
def get_input(prompt):
"""
This just wraps input()
:param prompt:
:return:
"""
return input(prompt)
def interactive_get_placement_coord(ship):
"""
Prompts a player to input a row, column, and horiz/vert
Return integers x, y and bool for horizontal
:param ship:
:return:
"""
# loop until we get valid entry
while True:
place_row = get_input(
"Specify starting row for " + ship.name + " (length: " + str(
ship.size) + ") [A-J]: ")
place_row = place_row.upper()
if not valid_row_input(place_row):
msg("Please enter a letter from A to J!")
else:
break
while True:
place_col = get_input(
"Specify starting column for " + ship.name + " (length: " + str(
ship.size) + ") [0-9]: ")
if not valid_column_input(place_col):
msg("Please enter a digit from 0 to 9!")
else:
break
while True:
hor_vert = get_input("Should ship run Horizontally, "
"or Vertically? [H|V]? ")
hor_vert = hor_vert.upper()
if hor_vert == "H":
horizontal = True
break
elif hor_vert == "V":
horizontal = False
break
else:
msg("Please enter H or V!")
x_coord = int(place_col)
y_coord = int(row_letter_to_y_coord_int(place_row))
return x_coord, y_coord, horizontal
def interactive_get_attack_coord():
"""
Prompts player to input row and column
Returns integers for x and y
:return:
"""
while True:
row_attack = get_input("Which row would you like to attack [A-J]? ")
row_attack = row_attack.upper()
if not valid_row_input(row_attack):
msg("Please enter a letter from A to J!")
else:
break
while True:
col_attack = get_input("Which column would you like to attack [0-9]? ")
if not valid_column_input(col_attack):
msg("Please enter a digit from 0 to 9!")
else:
break
x_coord = int(col_attack)
y_coord = int(row_letter_to_y_coord_int(row_attack))
return x_coord, y_coord
# HELPER FUNCTIONS #
def valid_row_input(row):
"""
Tests if string is single character from A to I
:type row: str
:rtype: bool
"""
if len(row) == 1 and row in ROWS:
return True
else:
return False
def valid_column_input(col):
"""
Tests if entered digit is within range
:type col: int
:rtype: bool
"""
# TODO handle type mismatch errors
if 0 <= int(col) <= 9:
return True
else:
return False
def row_letter_to_y_coord_int(row_letter):
"""
Translates a letter Y position into a numeric one
:type row_letter: str
:rtype: int
"""
# set up a dictionary mapping letters to numbers
# http://stackoverflow.com/a/14902938/7087237
row_dict = dict(zip(ROWS, range(0, len(ROWS))))
y_coord = row_dict[row_letter]
assert 0 <= y_coord <= 9
return y_coord
def anykey():
"""
Prompts user to press enter
:return:
"""
# TODO actually scan for any single keypress
input("- Press ENTER to continue. -")
|
1c292785fe64422067cbc000aa20434e37ed4b23 | PaulGood247/CloudComputing | /lab3.py | 371 | 3.734375 | 4 | #Lab 3
x= raw_input("Enter string: ") #Take in input
result= x[::-1] #[::-1] reverses string and stores in result
if (result ==x ):
print 'true'
else:
print 'false'
# I wrote the program first without any commits as my commits would not work, after i got help in lab i committed whole program. I understand the 4 commits were to follow the evolution of the program. |
ee9ad09d56da4c283502c95b8d93496b86535c7c | adrija24/languages_learning | /Python/Day 1/To reverse a number.py | 147 | 4.3125 | 4 | """To reverse a number"""
n=int(input("Enter the number: "))
s=0
while n!=0:
m = n%10
n=n//10
s=s*10+m
print("The reversed number: ",s) |
d8d1576ea84457e28e17e29cf98ba824779e838b | Ben-Rapha/Python-HWS | /my final project.py | 2,267 | 4.15625 | 4 | # CSI_31_KINGSLEY_OTTO_FINAL_PROJECT.PY
# THIS PROGRAM CHECKS A USER'S ID AND PASSWORD AGAINST A FILE.
import sys
# Introduction to the user
def intro():
print("This program asks the user for his/her user-ID and password and runs ")
print("it against a file of user-ID's and passwords.The user has only three")
print("attempt to get his/her user-ID's and passwords.")
print()
return intro
#Get user information
def getInput():
userID = input ("please enter your user-ID: ")
passW = input ("Please enter your user password: ")
print()
return userID,passW
def verify(userID,passW):
#Open file containing the user-ID and password
file = open("unames_passwords.txt", "r")
try :
for userpass in file:
name,passw = userpass.split()
if name == userID and passw == passW:
return True
else:
return False
except (ValueError,TypeError,NameError):
return False
def main():
intro()
attempt = 0
while attempt < 4 :
userID,passW = getInput()
attempt += 1
authentication = verify(userID,passW)
if authentication:
print("Your user-ID and Password is recognisable in our directory")
sys.exit()
else:
print("Invalid user-ID or password.Please try again")
if attempt == 3 :
print("Authentication failed. Your userID and password is unrecognisable in our system directory")
sys.exit()
main()
"""
This program asks the user for his/her user-ID and password and runs
it against a file of user-ID's and passwords.The user has only three
attempt to get his/her user-ID's and passwords.
please enter your user-ID: raymond
Please enter your user password: nash
Invalid user-ID or password.Please try again
please enter your user-ID: filarin
Please enter your user password: quaks
Invalid user-ID or password.Please try again
please enter your user-ID: jdoe
Please enter your user password: mutt
Your user-ID and Password is recognisable in our directory
"""
|
f79f080efbd43437b956556694302c3b346b4d56 | killstyles/my_love | /GUI.py | 411 | 3.59375 | 4 | from tkinter import *
class Application(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.helloLabel = Label1(self,text='Hello, world!')
self.helloLabel.pack()
self.quitButtom = Button(self, text='Quit', command=self.quit)
self.quitButton.pack()
app = Appliacation()
app.master.title('Hello world')
app.mainloop()
|
d7415d0451b8c69b21dbc017a35d3c8b2e526f1b | abdibogor/The-Bad-Tutorial | /05_Python/22_The Continue Statement/continue.py | 281 | 4.03125 | 4 | """
for var in range(1,16):
print(var)
"""
"""
for var in range(1,16):
if(var in range(9,14)):
continue
else:
print(var)
"""
print("Enter a string:")
var=input()
for letter in var:
if(letter==' '):
continue
else:
print(letter)
|
21eae74e12ec987cea69f6be9494e5f92c0dbd6a | eric496/leetcode.py | /hash_table/1189.maximum_number_of_balloons.py | 854 | 4.125 | 4 | """
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "loonbalxballpoon"
Output: 2
Example 3:
Input: text = "leetcode"
Output: 0
Constraints:
1 <= text.length <= 10^4
text consists of lower case English letters only.
"""
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
res = 0
while 1:
for ch in "balloon":
if ch in freq and freq[ch]:
freq[ch] -= 1
else:
return res
res += 1
|
e08d6ded70fe91e5ed59697b782093049c75ba41 | SuperAllenYao/pythonCode | /chapter_class/homework/Vehicle.py | 2,213 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Vehicle(object):
# 自定义Vehicle类属性
def __init__(self, speed: int, size: tuple, trans_type='SUV'):
# 自定义实例的初始化方法
self.trans_type = trans_type
self.speed = speed
self.size = size
# 自定义实例方法show_info,打印实例的速度和体积
def show_info(self):
print('我的所属类型为: {},速度:{}km/h,体积:{}'.format(self.trans_type, self.speed, self.size))
# 自定义实例方法move,打印“我已向前移动了50米”
def move(self):
print('我已向前移动了50米')
# 自定义实例方法set_speed,设置对应的速度值
def set_speed(self, new_speed):
self.speed = new_speed
# 自定义实例方法get_speed,打印当前的速度值
def get_speed(self):
print('我的时速为: {}km/h'.format(self.speed))
# 自定义实例方法speed_up,实现对实例的加速
def speed_up(self, up):
up_speed = '我的速度由{}km/h提升到了{} km/h'.format(self.speed, self.speed + up)
self.speed = self.speed + up
print(up_speed)
# 自定义实例方法speed_down,实现对实例的减速
def speed_down(self, down):
down_speed = '我的速度由{}km/h下降到了{} km/h'.format(self.speed, self.speed - down)
print(down_speed)
# 自定义实例方法transport_identify,实现对实例所属类型的判断
def transport_identify(self, belong):
if isinstance(belong, Vehicle) is True:
print('类型匹配')
else:
print('类型不匹配')
if __name__ == "__main__":
tool_1 = Vehicle(20, (3.6, 1.9, 1.75))
# 调用实例方法 打印实例的速度和体积
tool_1.show_info()
# 调用实例方法 实现实例的前移
tool_1.move()
tool_1.set_speed(40)
# 调用实例方法 打印当前速度
tool_1.get_speed()
# 调用实例方法 对实例进行加速
tool_1.speed_up(10)
# 调用实例方法 对实例进行减速
tool_1.speed_down(15)
# 调用实例方法 判断当前实例的类型
tool_1.transport_identify(tool_1)
|
ee9b5cf5959aa845d5b23d3bf00da67729184906 | Javaman1138/adventofcode | /day9.py | 3,496 | 3.59375 | 4 | test_data = ["London to Dublin = 464",
"London to Belfast = 518",
"Dublin to Belfast = 141",
"NY to Belfast = 100",
"NY to London = 200",
"NY to Dublin = 300"]
#test_data = ["London to Dublin = 464",
# "London to Belfast = 518",
# "Dublin to Belfast = 141"]
distances = {}
start_points = []
f1 = open('day9_data.txt', 'r')
for line in test_data:
distance_split = line.split("=")
miles = int(distance_split[1].strip())
name_split = distance_split[0].split('to')
name1 = name_split[0].strip()
name2 = name_split[1].strip()
print "{0} to {1} = {2}".format(name1, name2, miles)
if (distances.has_key(name1)):
distances_for_name1 = distances[name1]
distances_for_name1[name2] = miles
else:
distances[name1] = {name2: miles}
start_points.append(name1)
if (distances.has_key(name2)):
distances_for_name2 = distances[name2]
distances_for_name2[name1] = miles
else:
distances[name2] = {name1: miles}
start_points.append(name2)
print start_points
print distances
def start_to_end(start, end):
if not end:
return 0
print 'distance {0} to {1} = {2}'.format(start, end, distances[start][end])
return distances[start][end]
def traverse(visited, point, level):
children = [x for x in distances[point] if x not in visited]
pref = ""
for x in range(0,level):
pref += "."
print pref + 'POINT ' + point
print pref + 'child ' + str(children)
print pref + 'visit ' + str(visited)
if not children:
return 0
for idx, child in enumerate(children):
print pref + str(idx)
total = 0
if child not in visited:
child_visited = set(visited)
child_visited.add(child)
print pref + str(child_visited)
print pref + 'start to end {0} + {1} = {2}'.format(point, child, start_to_end(point, child))
return start_to_end(point, child) + traverse(child_visited, child, level+1)
#print total
else:
total += 0
print pref + 'sub total= ' + str(total) + '\n'
return total
def trav(visited, point, level, total):
pref = ""
for x in range(0,level):
pref += "."
print pref + point
print pref + str(visited)
children = [x for x in distances[point] if x not in visited]
print pref + str(children)
if not children:
return 0
for child in children:
new_visited = set(visited)
new_visited.add(child)
current_distance = start_to_end(point, child)
return current_distance + trav(new_visited, child, level+1, current_distance)
print 'test-----------'
print trav(set(['London']), 'London', 1, 0)
print '----------------\n'
print '- permutations version -'
min_distance = 99999999
max_distance = 0
import itertools
permutations = list(itertools.permutations(start_points))
for direction in permutations:
total_distance = 0
for idx in range(0, len(direction)-1):
total_distance += distances[direction[idx]][direction[idx+1]]
if total_distance < min_distance:
min_distance = total_distance
if total_distance > max_distance:
max_distance = total_distance
print 'min distance = ' + str(min_distance)
print 'max distance = ' + str(max_distance)
|
b7b9724183b9f38d3e4b1e86a0958bc8b0c6aba5 | Lan-Yang/Modern-Search-Engine | /query_answer.py | 3,618 | 3.671875 | 4 | import json
import urllib
# User input question in the format "Who created [X]?"
question_str = raw_input('Input your question like "Who created [X]?", X is a book name or a company name: ')
question = question_str.split()
length = len(question)
result_list = []
# Check input question's format
if (question[0].lower() != 'who' or question[1].lower() != 'created' or question[-1][-1] != '?'):
print 'Wrong input format!'
exit(1)
# Get [X]
search_term = ' '.join(question[2:])
search_term = search_term[:-1]
api_key = open("api_key").read()
service_url = 'https://www.googleapis.com/freebase/v1/mqlread'
# temp = '\t' + " -------------------------------------------------------------------------------------------------- " + '\t'
# print temp
# whitespace = ''
# for i in range((len(temp) - len(question_str) - 4)/2):
# whitespace += ' '
# if (len(temp) - len(question_str) - 4) % 2 == 0:
# question_str = '\t' + '|' + whitespace + question_str + whitespace + '|' + '\t'
# else:
# question_str = '\t' + '|' + whitespace + question_str + whitespace + ' ' + '|' + '\t'
# print question_str
# Treat X as substring of a book name, search its author's name
query = [{
"/book/author/works_written": [{
"a:name": None,
"name~=": search_term
}],
"id": None,
"name": None,
"type": "/book/author"
}]
params = {
'query': json.dumps(query),
'key': api_key
}
url = service_url + '?' + urllib.urlencode(params)
response = json.loads(urllib.urlopen(url).read())
author_dict = {}
business_dict = {}
# Format output result in the format "A (as XXX) created <X1>, <X2>, ... and <Xn>."
for author in response['result']:
tmp_list = []
tmp_str = ''
tmp_length = 0
name = author['name']
for book in author["/book/author/works_written"]:
tmp_list.append(book['a:name'])
author_dict[name] = tmp_list
tmp_length = len(tmp_list)
tmp_str = '%s (as Author) created <%s>' % (name, tmp_list[0])
tmp_length = tmp_length - 1
while (tmp_length > 1):
tmp_str = tmp_str + ', <%s>' % tmp_list[len(tmp_list) - tmp_length]
tmp_length = tmp_length - 1
if (tmp_length > 0):
tmp_str = tmp_str + ' and <%s>.' % tmp_list[len(tmp_list) - tmp_length]
result_list.append(tmp_str)
# Treat X as substring of a company name, search its businessperson's name
query = [{
"/organization/organization_founder/organizations_founded": [{
"a:name": None,
"name~=": search_term
}],
"id": None,
"name": None,
"type": "/organization/organization_founder"
}]
params = {
'query': json.dumps(query),
'key': api_key
}
url = service_url + '?' + urllib.urlencode(params)
response = json.loads(urllib.urlopen(url).read())
# Format output result in the format "A (as XXX) created <X1>, <X2>, ... and <Xn>."
for businessperson in response['result']:
tmp_list = []
tmp_str = ''
tmp_length = 0
name = businessperson['name']
for company in businessperson["/organization/organization_founder/organizations_founded"]:
tmp_list.append(company['a:name'])
business_dict[name] = tmp_list
tmp_length = len(tmp_list)
tmp_str = '%s (as BusinessPerson) created <%s>' % (name, tmp_list[0])
tmp_length = tmp_length - 1
while (tmp_length > 1):
tmp_str = tmp_str + ', <%s>' % tmp_list[len(tmp_list) - tmp_length]
tmp_length = tmp_length - 1
if (tmp_length > 0):
tmp_str = tmp_str + ' and <%s>.' % tmp_list[len(tmp_list) - tmp_length]
result_list.append(tmp_str)
# Sort lines alphabetically by <Name>
result_list.sort()
# Display result
count = 0
for each_result in result_list:
count += 1
print str(count) + ". " + each_result |
c8f0b3780e5811836c5247e517a402566c3d3468 | imsudheerkumar/Python-Programming | /sudheer_python_2/lower.py | 217 | 3.890625 | 4 | str=input("enter string")
count=0
count2=0
for i in str:
if(i.islower()):
count=count+1
elif (i.isupper()):
count2=count2+1
print("lower case :",count)
print("upper case :",count2)
|
1654f86e23d3aee828e722a1ac81923a01df2606 | manon2012/python | /work/leetcode/countprime.py | 420 | 3.609375 | 4 | def countPrimes( n):
"""
:type n: int
:rtype: int
"""
for i in range(2, n):
if n % i == 0:
# print ("not p")
# return False
break
else:
return True
# b = list(filter(countPrimes, range(2, 10)))
# print (b)
def getsum(n):
# a=[]
b = list(filter(countPrimes, range(2, n)))
# print (b)
# a.extend(b)
print(len(b))
getsum(10) |
8cbf620b8bbd1dbe2785a44ba0ba5217e4ef21a7 | tytyman5264/pdsnd_github | /bikeshare.py | 7,437 | 4.03125 | 4 | import time as t
import numpy as np
import pandas as pd
CITY_DATA = { 'chicago': 'chicago.csv',
'nyc': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters(city, month, day):
print ('Hello! Let\'s explore major US bikeshare data!')
print ('')
t.sleep(1)
while True:
print ("Which city do you want to explore its bikeshare data?\n")
answer = input("Chicago, NYC or Washington?\n").lower()
print ('')
if answer not in ("chicago", "nyc", "washington"):
print("\nInvalid answer\n")
continue
else:
break
print("\nNow how do you want to filter your data?\n")
data_filter = input("Month, day, both, or none?\n")
while True:
if data_filter not in ("month", "day", "both", "none"):
print("\nInvalid answer\n")
continue
elif data_filter == "month":
print("Which month do you want to explore? - please type in first three letters of month all in lowercase\n")
month = input("Jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec or all?\n").lower()
day = 'all'
while True:
if month not in ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "all"):
print("\nInvalid answer\n")
continue
else:
break
break
elif data_filter == "day":
print("Which day do you want to explore? - please type in first three letters of day all in lowercase\n")
day = input("Mon, tue, wed, thu, fri, sat, sun or all?\n").lower()
month = 'all'
while True:
if day not in ("mon", "tue", "wed", "thu", "fri", "sat", "sun", "all"):
print("\nInvalid answer\n")
continue
else:
break
break
elif data_filter == "both":
print("Which month do you want to explore? - please type in first three letters of month all in lowercase\n")
month = input("Jan, feb, mar, apr, may, jun, july, aug, sep, oct, nov, dec or all?\n").lower()
while True:
if month not in ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "all"):
print("\nInvalid answer\n")
continue
else:
break
print("Now which day do you want to explore? - please type in first three letters of day all in lowercase\n")
day = input("Mon, tue, wed, thu, fri, sat, sun or all?\n").lower()
while True:
if day not in ("mon", "tue", "wed", "thu", "fri", "sat", "sun", "all"):
print("\nInvalid answer\n")
continue
else:
break
elif data_filter == "none":
month = 'all'
day = 'all'
return city, month, day
def load_data(city, month, day):
df = pd.read_csv(CITY_DATA['chicago'])
df = pd.read_csv(CITY_DATA['nyc'])
df = pd.read_csv(CITY_DATA['washington'])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
if month != 'all':
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'aug', 'sep', 'oct', 'nov', 'dec']
month = months.index(month) + 1
df = df[df['month'] == month]
if day != 'all':
df = df[df['day_of_week'] == day]
return df
def time_stats(df):
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['time'] = df['Start Time'].dt.time
common_time = df['time'].mode()[0]
print('\nCalculating The Most Frequent Times of Travel...\n')
print('')
df['month'] = df['Start Time'].dt.month
common_month = df['month'].mode()[0]
print('Most Common Month:', common_month)
print('')
df['week'] = df['Start Time'].dt.week
common_week = df['week'].mode()[0]
print('Most Common day of week:', common_week)
print('')
df['hour'] = df['Start Time'].dt.hour
common_hour = df['hour'].mode()[0]
print('Most Common Start Hour:', common_hour)
print('')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
print('\nCalculating The Most Popular Stations and Trip...\n')
print('')
start_time = time.time()
df['Station'] = pd.to_string(df['Station'])
df['start'] = df['Station'].dt.start
common_start_station = df['start'].mode()[0]
print('Most Common Start Station:', common_start_station)
print('')
df['end'] = df['Station'].dt.start
common_end_station = df['end'].mode()[0]
print('Most Common End Station:', common_end_station)
print('')
df['combo'] = df['Start Station'] + ' to ' + df['End Station']
common_station_combo = df['combo'].mode().loc[0]
print('Most common Combination:', common_station_combo)
print('')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
print('\nCalculating Trip Duration...\n')
start_time = time.time()
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['total'] = df['Start Time'] + df['End Time']
total_travel_time = df['total'].mode()[0]
print('Total Travel Time:', total_travel_time)
print('')
df['average'] = df['total']
average = np.mean(df['total']).mode()[0]
print('Mean/Average Travel Time:', average)
print('')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
print('\nCalculating User Stats...\n')
start_time = time.time()
df['user_stats'] = pd.to_numeric(df['user_stats'])
df['user_types'] = df['user_stats'].dt.user_types
user_types = df['user_types'].value_counts()
print('Counts of user types:', user_types)
print('')
df['gender'] = df['user_stats'].dt.gender
gender = df['gender'].value_counts()
print('Counts of gender:', gender)
print('')
df['earliest_birth_year'] = df['Birth_Year'].dt.earliest_birth_year
earliest_birth_year = df['Birth_Year'].min()
print('Earliest Birth Year:', earliest_birth_year)
print('')
df['recent_birth_year'] = df['Birth_Year'].dt.recent_birth_year
recent_birth_year = df['Birth Year'].max()
print('Recent Birth Year:', recent_birth_year)
print('')
df['common_birth_year'] = df['Birth_Year'].dt.common_birth_year
common_birth_year = df['Birth Year'].mode()[0]
print('Most Popular Birth Year:', common_birth_year)
print('')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
city = ""
month = 0
day = 0
while True:
city, month, day = get_filters(city, month, day)
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
fef2bea17ffb60458cf22821fc4503494914b2ea | esselstyn/Homework_1 | /prime.Factor.py | 690 | 3.671875 | 4 | #!/usr/bin/env python
max = int(raw_input('Select the maximum value: '))
max = max + 1
#Make a list of all prime numbers between 1 and max
primes = []
for i in range(1, max):
x = 0
if i < 4:
primes.append(i)
else:
for j in range(2, i-1):
if i % j == 0:
x = 1
if x == 0:
primes.append(i)
##reduce the number to primes
for k in range(1, max):
if k in primes: ##if it is already a prime
answer = [k]
else:
z = 0
answer = []
for y in primes:
if y > 1:
while z not in primes:
if k % y == 0:
z = k / y
answer.append(y)
if z in primes:
answer.append(z)
break
else:
k = z
else:
break
print answer
|
ffd942f4497eb0eee211598e8fbb11c9c0954d8e | nishanthnandakumar/Artificial-Intelligence---Classes | /DepthFirstSearch.py | 4,678 | 3.859375 | 4 | #! /usr/bin/env python
import numpy as np
import time
#Define the start state
start_state = np.array([[1,2,3],[4,5,0],[7,8,6]])
#Define the goal state
goal = np.array([[1,2,3],[4,5,6],[7,8,0]])
#Define predecessor for start_state
base = (np.array([0]*9)).reshape(3,3) #creates a 3x3 array of zeros
#My input to the function
node_list = [None]
node_list[0] = np.array([base,start_state]) #creates an array of 2,3,3
#Initialise
new_nodes = []
all_nodes = []
#Defining the successor function
def switch_tile(zp,sf,node):
switch = np.copy(node)
temp = switch[zp[0]][zp[1]] #we are moving the tiles
switch[zp[0],zp[1]] = switch[sf[0],sf[1]]
switch[sf[0],sf[1]] = temp
return switch
def successor(node):
#First we need to know where the zero tile is located
zero_tile = np.argwhere(node==0) #Gives the location of zero in the node
zero_tile = zero_tile.flatten() #converts 2D to 1D
successor_state = [] #Empty list of succesor states
#shift the tile down
shift_tile = np.copy(zero_tile)
shift_tile[0] = shift_tile[0]+1 #shifting the zero tile down
if 0<=shift_tile[0]<=2 and 0<=shift_tile[1]<=2: #checking if it is within the boundary
down_shift_tile = switch_tile(zero_tile, shift_tile, node) #move the zero tile down and put the tile in zero position
down_shift_tile = np.array([node, down_shift_tile])
successor_state = successor_state + [down_shift_tile] #append to successor_state
#shift the tile up
shift_tile = np.copy(zero_tile)
shift_tile[0] = shift_tile[0]-1
if 0<=shift_tile[0]<=2 and 0<=shift_tile[1]<=2:
up_shift_tile = switch_tile(zero_tile, shift_tile, node)
up_shift_tile = np.array([node, up_shift_tile])
successor_state = successor_state + [up_shift_tile]
#shift the tile right
shift_tile = np.copy(zero_tile)
shift_tile[1] = shift_tile[1]+1
if 0<=shift_tile[0]<=2 and 0<=shift_tile[1]<=2:
right_shift_tile = switch_tile(zero_tile, shift_tile, node)
right_shift_tile = np.array([node, right_shift_tile])
successor_state = successor_state + [right_shift_tile]
#shift the tile left
shift_tile = np.copy(zero_tile)
shift_tile[1] = shift_tile[1]-1
if 0<=shift_tile[0]<=2 and 0<=shift_tile[1]<=2:
left_shift_tile = switch_tile(zero_tile, shift_tile, node)
left_shift_tile = np.array([node, left_shift_tile])
successor_state = successor_state + [left_shift_tile]
return successor_state #Return the list of all successor node_list
#Predecessor function
def predecessor(node):
global path, all_nodes
compare = node == start_state #checking if we have reached the start state
if compare.all() == True:
print(np.array(path)) #if so just print the node alone
quit()
else:
for k in range(len(all_nodes)): #its a 2D array
if (all_nodes[k][1]==node).all() == True: # we are checking if the node is same as the required node
new_node = all_nodes[k][0] #we are taking the node which generated this node
path = path + [new_node] #appending this to path
predecessor(new_node) #we are checking the previous state
k += 1 #increment by 1
#Depth first search function based on the pseudo code provided
def dpt_fst_sch(node_list, goal):
global f_c, new_nodes
global n_c, all_nodes, path
compare = node_list[0][1] == goal #we are comparing the start state to goal
if compare.all() == True:
result = 1 #we have reached the goal node
return result
else:
new_nodes = new_nodes+ successor(node_list[0][1])
f_c += 1 #increasing the depth count
all_nodes = all_nodes + new_nodes #we are appending the new_nodes to all_nodes
if f_c > 100: #just to not end up in an infinite loop
print('Depth limit reached!')
quit()
while new_nodes != []:
result = dpt_fst_sch(new_nodes, goal) #It takes the first succesor and expands it and keeps continuing
if result == 1:
print('Goal state reached: \n{}'.format(new_nodes[0][1]))
print('Solution found at depth {}'.format(f_c))
print('Total nodes generated {}'.format(n_c))
print('Time Taken to solve: {}'.format(time.clock()-s_t))
print('Predecessor path is as follows:')
path = [new_nodes[0][1]]
predecessor(new_nodes[0][1])
else:
new_nodes = new_nodes[1:] #we are removing the first node
return("No Solution")
f_c = 0
n_c = 0
#calling my main function
s_t = time.clock()
dpt_fst_sch(node_list,goal)
|
ed1c05fe519969bec206b609b99388c8ed1c5d7c | pedrohenriquebraga/Curso-Python | /Mundo 2/Exercícios/ex_042.py | 487 | 4.09375 | 4 | # DIZ QUAL TIPO DE TRIÂNGULO SE FORMARÁ
r1 = float(input("Digite a 1° reta: "))
r2 = float(input("Digite a 2° reta: "))
r3 = float(input("Digite a 3° reta: "))
if r1 + r2 > r3 and r1 + r3 > r2 and r2 + r3 > r1:
print("Essas retas podem FORMAR um triângulo", end=" ")
if r1 == r2 == r3:
print("EQUILÁTERO!!")
elif r1 != r2 != r3 != r1:
print("ESCALENO!!")
else:
print("ISÓSCELES!!")
else:
print("Esse triângulo não pode existir!!")
|
6a5a75a3e3f0d05d0dc4a487ef5f56836b8d40a7 | Sasha2508/Python-Codes | /Others/Date_time_scraper.py | 2,413 | 3.671875 | 4 | # extracting time and date from the below website
# https://www.timeanddate.com/
"""Python Program to Quickly fetch date and time from https://www.timeanddate.com/ and copy it to clipboard"""
from bs4 import BeautifulSoup
import requests
import re
import time
from _datetime import datetime
import pyperclip as pc
def filter_date(date_string):
Match_string = re.match(f"^(\S*), (\d*) (\D*) (\d*)", date_string)
week_day = Match_string.group(1)
date2 = Match_string.group(2)
month = Match_string.group(3)
year = Match_string.group(4)
return week_day, date2, month, year
def filter_time(time_string):
y_time = re.match('(\d*):(\d*):(\d*)', time_string)
hr = y_time.group(1)
minute = y_time.group(2)
sec = y_time.group(3)
return hr, minute, sec
if __name__ == '__main__':
country = 'india' # input('Enter your country:')
city = 'kolkata' # input('Enter your city:')
# url = 'https://www.timeanddate.com/worldclock/india/kolkata'
url = f'https://www.timeanddate.com/worldclock/{country}/{city}'
headers = {"Accept-Language": "en-US,en;q=0.5"}
r = requests.get(url, headers=headers)
print(f'Status Code: {r.status_code}') # permission status code, 200 - allowed, other wise = not allowed
data = r.content
soup = BeautifulSoup(data, "html5lib")
# print(soup.prettify())
time = soup.find_all('span', {"class": "h1"})[0].text # gets the current local time from the given website
print(f'Current local time: {time}')
date = soup.find_all("span", {"id": "ctdat"})[0].text # gets the current local date from the given website
print(f'Current local date: {date}')
week_day, day, mnth, year = filter_date(date)
hr, minute, sec = filter_time(time)
# print(f'{day},{mnth},{year},{hr},{minute},{sec}')
week_days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct', 'nov', 'dec']
for i in months:
if mnth.lower().startswith(i):
mnth = months.index(i) + 1
break
# print(f'month={mnth}')
week_day_no = week_days.index(week_day.lower()) + 1
time_tuple = (int(year), int(mnth), week_day_no, int(day), int(hr), int(minute), int(sec), 0)
# just copy the date and time to the clip board
pc.copy(time + '.0')
print("Time copied!")
|
bb433f82a9722876ebf6656cd9021a1122951e14 | ca-sousa/py-guanabara | /exercicio/ex083.py | 333 | 3.75 | 4 | exp = input('Digite a expressao: ')
lista = []
for simb in exp:
if simb == '(':
lista.append('(')
elif simb == ')':
if len(lista) > 0:
lista.pop()
else:
lista.append(')')
if len(lista) == 0:
print('Sua expressao esta valida!')
else:
print('Sua expressao esta errada!') |
e8e659384627ab0094cd3c613309e807c1f4bd53 | liuyiquanGoodCoder/dataStructure | /2.二维数组中的查找.py | 523 | 3.5625 | 4 | class Solution:
def Find(self,target,array):
rows = len(array)
cols = len(array[0])
if rows > 0 and cols > 0:
row = 0
col = cols - 1
while row < rows and col >= 0:
if target == array[row][col]:
return True
elif target < array[row][col]:
col -= 1
else:
row += 1
return False
array = [[1,2,3],[4,5,6],[7,8,9]]
obj = Solution()
obj.Find(10,array) |
00bcb3370287c3a39d2b7e2cd5aeb15bed68a095 | Aasthaengg/IBMdataset | /Python_codes/p02722/s721857909.py | 420 | 3.609375 | 4 | def main():
n = int(input())
count = 2
sqrt = int(n ** (1/2))
for i in range(2,sqrt + 1):
if n % i == 1:
count += 2
elif n % i == 0:
ins = n
while ins % i == 0:
ins = ins // i
if ins % i == 1:
count += 1
if sqrt ** 2 == n - 1:
count -= 1
print(count)
if __name__ == "__main__":
main()
|
f0e85dfb641bcb7822e9d18ac9f555a33869cbb5 | Hehwang/Leetcode-Python | /code/098 Validate Binary Search Tree.py | 968 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.flag=True
def helper(self,root,max_num,min_num):
if root.left:
if root.left.val<=min_num or root.left.val>=max_num or root.left.val>=root.val:
self.flag=False
self.helper(root.left,min(max_num,root.val),min_num)
if root.right:
if root.right.val<=min_num or root.right.val>=max_num or root.right.val<=root.val:
self.flag=False
self.helper(root.right,max_num,max(min_num,root.val))
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
max_num=2**32
min_num=-2**32
self.helper(root,max_num,min_num)
return self.flag |
8286af2a6376ff3340ca8d0d6c82f78bfb42033b | romirmoza/advent-of-code-2019 | /advent-of-code-2019/day1_rocket_equation.py | 579 | 3.984375 | 4 | def calculate_fuel_req(module):
return (module // 3) - 2
def calculate_fuel_req_recursive(module):
req = (module // 3) - 2
if req > 0:
return req + calculate_fuel_req_recursive(req)
return 0
if __name__ == '__main__':
file = open('day1_input.txt', 'r')
modules = list(map(int, file.read().split()))
reqa = sum([calculate_fuel_req(mod) for mod in modules])
reqb = sum([calculate_fuel_req_recursive(mod) for mod in modules])
print('Total fuel required = {}'.format(reqa))
print('Total fuel required recursive = {}'.format(reqb))
|
aea69a498caab1fe218aa0df397d93e9e5a937d7 | alexanch/Data-Structures-implementation-in-Python | /BST.py | 2,038 | 4.28125 | 4 | """ Binary Search Tree Implementation: search, insert, print methods. """
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
return self.insert_helper(self.root,new_val)
def insert_helper(self,start,new_val):
"""
Helper function for recursive insert method.
"""
if new_val>start.value:
if start.right:
self.insert_helper(start.right,new_val)
else:
start.right = Node(new_val)
elif new_val<start.value:
if start.left:
self.insert_helper(start.left,new_val)
else:
start.left = Node(new_val)
def search(self, find_val):
return self.search_helper(self.root,find_val)
def search_helper(self, start, find_val):
"""
Helper function for recursive search method.
"""
if start:
if start.value == find_val:
return True
elif find_val>start.value:
return self.search_helper(start.right,find_val)
elif find_val<start.value:
return self.search_helper(start.left,find_val)
return False
def print_tree(self):
return self.print_helper(self.root)[:-1]
def print_helper(self,next,traversal =''):
"""
Helper function for recursive print method.
"""
if next:
traversal +=(str(next.value)+'-')
traversal = self.print_helper(next.left, traversal)
traversal = self.print_helper(next.right,traversal)
return traversal
"""
Test case:
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Should be True
print tree.search(4)
# Should be False
print tree.search(6)
"""
|
a3652f393a0b4f52495d868c041f1b029b3370c7 | Dmarchand97/practicepython-practice | /rockPaper.py | 937 | 3.953125 | 4 | #Rock paper scissors
#Make a two-player Rock-Paper-Scissors game
#Rock beats scissors
#Scissors beats paper
#Paper beats rock
player1 = input("rock, paper, or scissors?... ")
player2 = input("rock, paper, or scissors?... ")
def winner(u1, u2):
if u1 == u2:
return("Its a tie! Try again!")
elif u1 == "rock":
if u2 == 'scissors':
return("Rock Wins! Play Again...?")
else:
return("Paper Wins! Play Again...?")
elif u1 == "scissors":
if u2 == 'paper':
return("scissors Wins! Play Again...?")
else:
return("rock Wins! Play Again...?")
elif u1 == "paper":
if u2 == 'rock':
return("paper Wins! Play Again...?")
else:
return("scissors Wins! Play Again...?")
else:
return("NO! WRONG! INVALID! ONLY ROCK, PAPER, SCISSORS!!!")
print(winner(player1, player2)) |
1871cfbc1dac1761365d1666bc0436413883caf9 | shinkai-tester/python_beginner | /Lesson10/tree.py | 540 | 3.5625 | 4 | N = int(input())
d = dict()
for i in range(N):
info = input().split()
parent = info[0]
childs = info[1:]
for child in childs:
d[child] = parent
if parent not in d:
d[parent] = None
N = int(input())
for i in range(N):
zapros = input().split()
parent = zapros[0]
child = zapros[1]
while child != parent and child is not None:
child = d[child]
if child is None:
print('NO')
else:
print('YES')
'''
8
A B C D
B F G
F O I
F P
Alexei Stepan Misha
Vladimir Alexei
Stepan Ilya
Misha Egor Dima
''' |
695c94bd3e989a63be1202ffedc6dbb8e52ce9ca | pawdon/python_course | /week05_day02/egz_zad3.py | 1,674 | 3.5 | 4 | import tkinter as tk
def run():
main_window = tk.Tk()
main_window.title("Klawisz")
main_window.geometry('700x700')
panel_width = 500
panel_height = 500
label_width = 100
label_height = 25
available_width = panel_width - label_width
available_height = panel_height - label_height
panel = tk.Frame(main_window, bg='#ffff00', height=500, width=500)
panel.grid(row=0, column=1)
label = tk.Button(panel, bg='#00ffff')
label.place(width=100, height=25)
vertical_var = tk.DoubleVar()
horizontal_var = tk.DoubleVar()
vertical_var.set(0)
horizontal_var.set(0)
def set_text():
label.configure(text=f'{horizontal_var.get()}, {vertical_var.get()}')
def move(val):
# val jest aktualną wartością slidera, który wywołał tą funkcję
# ale my tego nie potrzebujemy, bo mamy vertical_var i horizontal_var
label.place(width=label_width, height=label_height,
x=horizontal_var.get() * available_width,
y=vertical_var.get() * available_height)
set_text()
slider_vertical = tk.Scale(main_window, variable=vertical_var, from_=0, to=1, resolution=0.01,
orient=tk.VERTICAL, showvalue=False, command=move)
slider_vertical.grid(row=0, column=0, sticky=tk.NS)
slider_horizontal = tk.Scale(main_window, variable=horizontal_var, from_=0, to=1, resolution=0.01,
orient=tk.HORIZONTAL, showvalue=False, command=move)
slider_horizontal.grid(row=1, column=1, sticky=tk.EW)
set_text()
main_window.mainloop()
if __name__ == '__main__':
run()
|
cb2b5d569fadd2f4cf207a0067e18d3a216aca8d | pillowfication/ECS-32B | /Homework6/hw6_tools.py | 6,325 | 3.8125 | 4 |
#### Functions and classes to help with Homework 6
#### You should not make any changes to the functions and classes in this file,
#### but you should understand what they do and how they work.
import sys
### This function will be re-defined in hw6.py. However, it is needed for ExpTree,
### so it is redefined here as well. Do not modify this function, modify the
### one in hw6.py!
def printexp(tree):
sVal = ""
if tree:
sVal = '(' + printexp(tree.getLeftChild())
sVal = sVal + str(tree.getRootVal())
sVal = sVal + printexp(tree.getRightChild())+')'
return sVal
class ExpTree:
def __init__(self,key):
self.key = key
self.leftChild = None
self.rightChild = None
def setRightChild(self, child):
self.rightChild = child
def setLeftChild(self, child):
self.leftChild = child
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
return self.key
def __str__(self):
sVal = printexp(self)
return sVal
class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
def addVertex(self,key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertices[key] = newVertex
return newVertex
def getVertex(self,n):
if n in self.vertices:
return self.vertices[n]
else:
return None
def __contains__(self,n):
return n in self.vertices
def addEdge(self,f,t,cost=0):
if f not in self.vertices:
nv = self.addVertex(f)
if t not in self.vertices:
nv = self.addVertex(t)
self.vertices[f].addNeighbor(self.vertices[t],cost)
def getVertices(self):
return list(self.vertices.keys())
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self,num):
self.id = num
self.connectedTo = {}
self.color = 'white'
self.dist = sys.maxsize
self.pred = None
self.disc = 0
self.fin = 0
# def __lt__(self,o):
# return self.id < o.id
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def setColor(self,color):
self.color = color
def setDistance(self,d):
self.dist = d
def setPred(self,p):
self.pred = p
def setDiscovery(self,dtime):
self.disc = dtime
def setFinish(self,ftime):
self.fin = ftime
def getFinish(self):
return self.fin
def getDiscovery(self):
return self.disc
def getPred(self):
return self.pred
def getDistance(self):
return self.dist
def getColor(self):
return self.color
def getConnections(self):
return self.connectedTo.keys()
def getWeight(self,nbr):
return self.connectedTo[nbr]
def __str__(self):
return str(self.id) + ":color " + self.color + ":disc " + str(self.disc) + ":fin " + str(self.fin) + ":dist " + str(self.dist) + ":pred \n\t[" + str(self.pred)+ "]\n"
def getId(self):
return self.id
class PriorityQueue:
def __init__(self):
self.heapArray = [(0,0)]
self.currentSize = 0
def buildHeap(self,alist):
self.currentSize = len(alist)
self.heapArray = [(0,0)]
for i in alist:
self.heapArray.append(i)
i = len(alist) // 2
while (i > 0):
self.percDown(i)
i = i - 1
def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapArray[i][0] > self.heapArray[mc][0]:
tmp = self.heapArray[i]
self.heapArray[i] = self.heapArray[mc]
self.heapArray[mc] = tmp
i = mc
def minChild(self,i):
if i*2 > self.currentSize:
return -1
else:
if i*2 + 1 > self.currentSize:
return i*2
else:
if self.heapArray[i*2][0] < self.heapArray[i*2+1][0]:
return i*2
else:
return i*2+1
def percUp(self,i):
while i // 2 > 0:
if self.heapArray[i][0] < self.heapArray[i//2][0]:
tmp = self.heapArray[i//2]
self.heapArray[i//2] = self.heapArray[i]
self.heapArray[i] = tmp
i = i//2
def add(self,k):
self.heapArray.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
def delMin(self):
retval = self.heapArray[1][1]
self.heapArray[1] = self.heapArray[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapArray.pop()
self.percDown(1)
return retval
def isEmpty(self):
if self.currentSize == 0:
return True
else:
return False
def decreaseKey(self,val,amt):
# this is a little wierd, but we need to find the heap thing to decrease by
# looking at its value
done = False
i = 1
myKey = 0
while not done and i <= self.currentSize:
if self.heapArray[i][1] == val:
done = True
myKey = i
else:
i = i + 1
if myKey > 0:
self.heapArray[myKey] = (amt,self.heapArray[myKey][1])
self.percUp(myKey)
def __contains__(self,vtx):
for pair in self.heapArray:
if pair[1] == vtx:
return True
return False
def dijkstra(aGraph,start):
pq = PriorityQueue()
start.setDistance(0)
pq.buildHeap([(v.getDistance(),v) for v in aGraph])
while not pq.isEmpty():
currentVert = pq.delMin()
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() \
+ currentVert.getWeight(nextVert)
if newDist < nextVert.getDistance():
nextVert.setDistance( newDist )
nextVert.setPred(currentVert)
pq.decreaseKey(nextVert,newDist)
|
9b358371cc16a6c33a925269a6858e35db8475b5 | raffivar/NextPy | /unit_3/blog.py | 3,583 | 3.65625 | 4 | import string
class UsernameTooShort(Exception):
def __init__(self, username):
self._username = username
def __str__(self):
return "Username too short."
class UsernameContainsIllegalCharacter(Exception):
def __init__(self, username):
self._username = username
def __str__(self):
return "Username contains illegal character."
class UsernameTooLong(Exception):
def __init__(self, username):
self._username = username
def __str__(self):
return "Username too long."
def get_password(self):
return self._username
class PasswordTooShort(Exception):
def __init__(self, password):
self._password = password
def __str__(self):
return "Password too short."
class PasswordTooLong(Exception):
def __init__(self, password):
self._password = password
def __str__(self):
return "Password too long."
class PasswordMissingCharacter(Exception):
def __init__(self, password):
self._password = password
def __str__(self):
return "The password is missing a character"
def get_password(self):
return self._password
class Uppercase(PasswordMissingCharacter):
def __str__(self):
return super(Uppercase, self).__str__() + " (Upercase)"
class Lowercase(PasswordMissingCharacter):
def __str__(self):
return super(Lowercase, self).__str__() + " (Lowercase)"
class Digit(PasswordMissingCharacter):
def __str__(self):
return super(Digit, self).__str__() + " (Digit)"
class Special(PasswordMissingCharacter):
def __str__(self):
return super(Special, self).__str__() + " (Special)"
def check_username(username):
for char in username:
if not char.isalpha() and not char.isdigit() and char != "_":
raise UsernameContainsIllegalCharacter(username)
def check_password(password):
char_dict = {"upper": 0, "lower": 0, "digit": 0, "special": 0}
for char in password:
if char.isupper():
char_dict["upper"] += 1
elif char.islower():
char_dict["lower"] += 1
elif char.isnumeric():
char_dict["digit"] += 1
elif char in string.punctuation:
char_dict["special"] += 1
if char_dict["upper"] == 0:
raise Uppercase(PasswordMissingCharacter)
elif char_dict["lower"] == 0:
raise Lowercase(PasswordMissingCharacter)
if char_dict["digit"] == 0:
raise Digit(PasswordMissingCharacter)
if char_dict["special"] == 0:
raise Special(PasswordMissingCharacter)
def check_input(username, password):
try:
if len(username) < 3:
raise UsernameTooShort(username)
elif len(username) > 16:
raise UsernameTooLong(username)
check_username(username)
if len(password) < 8:
raise PasswordTooShort(password)
elif len(password) > 40:
raise PasswordTooLong(password)
check_password(password)
except Exception as e:
print(e)
else:
print("OK")
def main():
check_input("1", "2")
check_input("0123456789ABCDEFG", "2")
check_input("A_a1.", "12345678")
check_input("A_1", "2")
check_input("A_1", "ThisIsAQuiteLongPasswordAndHonestlyUnnecessary")
check_input("A_1", "abcdefghijklmnop")
check_input("A_1", "ABCDEFGHIJLKMNOP")
check_input("A_1", "ABCDEFGhijklmnop")
check_input("A_1", "4BCD3F6h1jk1mn0p")
check_input("A_1", "4BCD3F6.1jk1mn0p")
if __name__ == "__main__":
main()
|
08d8388793de65be7842ec1a6c5dd8274de3c033 | gowthamgoli/Leetcode | /contains_duplicate_217.py | 153 | 3.71875 | 4 | def containsDuplicate(nums):
num_map = {}
for num in nums:
if num in num_map: return True
else: num_map[num] = 1
return False |
6cd18013674944cba983235dd590bacc5fc1e726 | Bellroute/algorithm | /python/book_python_algorithm_interview/ch14/balanced_binary_tree.py | 1,269 | 3.859375 | 4 | # 리트코드 110. Balanced Binary Tree
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# 내 풀이
def isBalanced_mySolution(self, root: TreeNode) -> bool:
def get_height(root):
if not root:
return 0
return max(get_height(root.left), get_height(root.right)) + 1
if not root:
return True
left = get_height(root.left)
right = get_height(root.right)
if abs(left - right) > 1:
return False
if self.isBalanced(root.left) and self.isBalanced(root.right):
return True
else:
return False
# 책 풀이. 재귀 구조로 높이 차이 계산
def isBalanced(self, root: TreeNode) -> bool:
def check(root):
if not root:
return 0
left = check(root.left)
right = check(root.right)
# 높이 차이가 나는 경우 -1, 이외에는 높이에 따s라 1 증가
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
return check(root) != -1
|
c3b8f9c060b465cf9534dd219f206cb551c3ff4a | gwahak/Pygame | /Lesson07/GomokuClient/ChessboardClient.py | 2,186 | 3.5625 | 4 | import pygame
from Lesson07.Chessboard import Chessboard
class ChessboardClient(Chessboard):
def __init__(self):
super().__init__()
self.grid_size = 26
self.start_x, self.start_y = 30, 50
self.edge_size = self.grid_size / 2
def is_in_area(self, x, y):
return self.start_x <= x <= self.start_x + self.get_size() and \
self.start_y <= y <= self.start_y + self.get_size()
def get_size(self):
return (self.grid_count - 1) * self.grid_size + self.edge_size * 2
def get_r_c(self, x, y):
origin_x = self.start_x - self.edge_size
origin_y = self.start_y - self.edge_size
x -= origin_x
y -= origin_y
r = int(y // self.grid_size)
c = int(x // self.grid_size)
return r, c
def draw(self, screen):
# 棋盤底色
pygame.draw.rect(screen, (185, 122, 87),
[self.start_x - self.edge_size, self.start_y - self.edge_size,
(self.grid_count - 1) * self.grid_size + self.edge_size * 2,
(self.grid_count - 1) * self.grid_size + self.edge_size * 2], 0)
for r in range(self.grid_count):
y = self.start_y + r * self.grid_size
pygame.draw.line(screen, (0, 0, 0), [self.start_x, y],
[self.start_x + self.grid_size * (self.grid_count - 1), y], 2)
for c in range(self.grid_count):
x = self.start_x + c * self.grid_size
pygame.draw.line(screen, (0, 0, 0), [x, self.start_y],
[x, self.start_y + self.grid_size * (self.grid_count - 1)], 2)
for r in range(self.grid_count):
for c in range(self.grid_count):
piece = self.grid[r][c]
if piece != '.':
if piece == 'b':
color = (0, 0, 0)
else:
color = (255, 255, 255)
x = self.start_x + c * self.grid_size
y = self.start_y + r * self.grid_size
pygame.draw.circle(screen, color, [x, y], self.grid_size // 2)
|
5995d1228a9708410a822c5d17c6508f5b8c0de1 | callrua/spotipyutils | /src/genre_to_playlist.py | 3,174 | 3.546875 | 4 | """This script generates a spotify playlist of up to 100 songs based on given genres"""
import argparse
import spotipy
import spotipy.util as util
import os
import datetime
from pprint import pprint
import sys
parser = argparse.ArgumentParser(description='Args')
parser.add_argument('--genres', '-g', dest='genres', required=True, nargs='+',
help='Specify the genre(s) of music you wish to create a playlist for. '
'The list should be space seperated e.g. trance hip-hop trip-hop')
parser.add_argument('--track-limit', '-l', dest='limit', type=int, default=100, required=False,
help='The maximum number of tracks you want on the playlist')
parser.add_argument('--user-id', '-u', dest='uid', required=True,
help='Your spotify userID')
args = parser.parse_args()
class Spotify:
def __init__(self):
self.uid = args.uid
self.genres = args.genres
self.limit = args.limit
self.modify_scope = 'playlist-modify-public'
self.token = util.prompt_for_user_token(username=self.uid, scope=self.modify_scope)
self.spotify = spotipy.Spotify(auth=self.token)
self.curr_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.playlist_name = ("%s %s" % (str(self.genres), str(self.curr_time)))
def main(self):
accepted_genre_list = self.spotify.recommendation_genre_seeds()['genres']
for i in self.genres:
if i not in accepted_genre_list:
print("ERROR\n%s is not a recognised genre. "
"Please choose any from the following list of accepted genres:\n" % i)
pprint("%s" % accepted_genre_list)
sys.exit(1)
set_playlist_name(self)
create_blank_playlist(self)
populate_playlist(self)
def create_blank_playlist(self):
self.spotify.user_playlist_create(user=self.uid, name=self.playlist_name)
def set_playlist_name(self):
self.playlist_name = ("%s %s" % (str(self.genres), str(self.curr_time)))
playlist_name = ''
for i in self.genres:
playlist_name += i + "/"
self.playlist_name = "%s %s" % (playlist_name[:-1], str(self.curr_time))
def populate_playlist(self):
tracks = []
playlists = self.spotify.user_playlists(user=self.uid)
while playlists:
for i, playlist in enumerate(playlists['items']):
if self.playlist_name in playlist['name']:
while len(tracks) < self.limit:
reccs = self.spotify.recommendations(seed_genres=self.genres, limit=1, country='GB')
for j, track in enumerate(reccs['tracks']):
tracks.append(track['id'])
self.spotify.user_playlist_add_tracks(user=self.uid, playlist_id=playlist['id'], tracks=tracks)
print("Succesfully added %s songs to your new playlist %s\nENJOY :)"
% (self.limit, self.playlist_name))
if playlists['next']:
playlists = self.spotify.next(playlists)
else:
playlists = None
if __name__ == '__main__':
Spotify().main()
|
d7c0b8eb61709701ecd31442aed1043934caca1e | b-franka/after-advanced-algorithms | /python/binary_search.py | 532 | 3.90625 | 4 | import math
def search(num, array):
lowerIndex = 0
higherIndex = len(array) - 1
while lowerIndex <= higherIndex:
med = math.floor((lowerIndex + higherIndex) / 2)
pivot = array[med]
if pivot == num:
return med
elif num < pivot:
higherIndex = med-1
elif num > pivot:
lowerIndex = med+1
return -1
def main():
array = [1, 2, 10, 12, 17, 18, 19, 20, 23, 24, 25, 26, 27, 29, 30, 31, 33, 34, 36, 37]
print(search(30, array))
main() |
cc65a22ca924be9ff56650d485514e527970a3ff | mooksys/Python_Algorithms | /Chapter27/file_27_4c.py | 150 | 3.59375 | 4 | s = "I have a dream"
letter = input("검색할 영문자를 입력하여라: ")
if letter in s:
print("문자", letter, "를 찾았습니다.")
|
f56d40127957476bfba201659b8d491cefb518aa | khangtran123/Yaml_to_JSON_Converter | /Dictionary_Orion.py | 3,960 | 3.546875 | 4 | #!/usr/bin/python3
'''
Author: Khang Tran
Date: September 4, 2020
Parameters:
yamlFile: Please replace current param with the actual location of yaml file
jsonFile: Please replace current location of where the json file is stored
What I want to do is create a for loop that iterates through yaml file and checks key length (8 Characters CLLI)
if yes --> streamline to JSON dump
if no --> disregard
'''
import yaml
import json
import sys
yamlFile = "C:/Users/T944589/Documents/TNI/TNI-Website/YAML_Python_Dictionary/clli_out.yaml"
jsonFile = "C:/Users/T944589/Documents/TNI/TNI-Website/YAML_Python_Dictionary/sample_json.json"
delete_clliList = []
'''
Function: parse_through_dict()
Purpose: This function will recursively iterate and parse through the nested dictionary to get key "CLLI"
- Once I iterate through list --> Remove from buildings CLLI that are longer than 8 chars
'''
def parse_through_dict(yaml_dict):
# First going to iterate through yaml_dict keys via Province Code (ie. AB, BC)
for provCode in yaml_dict.keys():
# Then going to iterate through the City Code within the matched Province Code (Nested Dictionary)
for cityCode in yaml_dict[provCode].keys():
# Now that we are in the nested dict of Province --> City, want to iterate through building code nested in matched provCode-->cityCode
for buildingCode in yaml_dict[provCode][cityCode].keys():
# Condition to check for CLLI that are over 8 chars
if (len(buildingCode) > 8):
# will append matched keys within nested dictionary Province --> City --> Building to temp list
delete_clliList.append({'provCode' : provCode, 'cityCode' : cityCode, 'buildingCode' : buildingCode})
# This will iterate through the delete_clliList list and match nested key elements based on Province Code-->City Code-->Building Code
for item in delete_clliList:
if type(yaml_dict[item["provCode"]][item["cityCode"]][item["buildingCode"]]) is dict:
del yaml_dict[item["provCode"]][item["cityCode"]][item["buildingCode"]]
# Going to write the new yaml_dict in json file
with open(jsonFile,"w", newline='\n') as json_file:
# json.dump() streamlines dict object and writes it into json file
# indent=2 allows you to add new lines (Adds each dictionary entry onto a new line)
json.dump(yaml_dict, json_file, indent=2)
'''
*********** DO NOT DELETE -- RECURSION ***********
for key, value in yaml_dict.items():
with open(jsonFile,"w", newline='\n') as json_file:
# this is where recursion happens --> get's called repetitively if value of each item in directory is dict directory itself
if (type(value) is dict):
# here we are printing out all the keys in the current nested dictionary
if (len(key) <= 8):
print ("Key: " + key)
parse_through_dict(value)
else:
#print(key + ":" + value)
output = key + ":" + value
print(output)
#json.dump(new_dict, json_file, indent=2)
*********** DO NOT DELETE -- RECURSION ***********
'''
'''
Function: convert()
Purpose: Main Function that will read in CLLI YAML file and call on parse_through_dict()
'''
def convert():
with open(yamlFile, 'r') as yaml_file:
try:
print("******* Operation Beginning *******")
yaml_data = yaml.safe_load(yaml_file) # yaml_data parses the yaml file as a stream and outputs into python dict
parse_through_dict(yaml_data)
print("******* Operation Completed *******")
except yaml.YAMLError as error:
print(error)
convert() |
4e9be8c38712a92dba7971af7614bbe171573a41 | rafaelrbnet/curso-completo-de-python | /Aulas/02-Estruturas de Decisão/laco3.py | 362 | 3.796875 | 4 | servidores = ["dns", "database", "webserver", "voip", "mongodb"]
# O comando continue é usado para trabalhar com exeção de uma lista.
for s in servidores:
if s == "webserver":
print("O servidor {} não pode estar na lista".format(s))
break
else:
print("Todos os servidores estão atualizados")
print("Finalizando o programa")
|
de6325423e09e5e27e063e8e7d4fb9ce66315afe | farahzuot/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/tree/tree.py | 4,540 | 3.796875 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self,data): # 1 -> 2 -> none
node = Node(data)
if self.front == None:
self.front = node # 1 - >
else:
self.rear = self.front
current = self.rear # curr = node(1)
while current:
if current.next == None:
current.next = node
break
current = current.next
def dequeue(self):
try:
self.front = self.front.next
except AttributeError:
return ('Empty stack!')
def peek(self):
try:
return self.front.value
except AttributeError:
return ('Empty stack!')
def isEmpty(self):
if self.front:
return False
else:
return True
def __str__(self):
result=''
current = self.front
if current == None:
result = 'Empty stack!'
else:
while current:
result += f'{current.value} -> '
current = current.next
result += 'None'
return result
class NodeTwo:
def __init__(self,value):
self.value=value
self.right=None
self.left=None
class BinaryTree():
def __init__(self):
self.root=None
self.arr=[]
def preOrder(self):
try:
result = []
def internal(node):
result.append(node.value)
if node.left:
internal(node.left)
if node.right:
internal(node.right)
internal(self.root)
return result
except AttributeError:
return []
def inOrder(self):
try:
result=[]
def internal(node):
if node.left:
internal(node.left)
result.append(node.value)
if node.right:
internal(node.right)
internal(self.root)
return result
except AttributeError:
return []
def postOrder(self):
try:
result=[]
def internal(node):
if node.left:
internal(node.left)
if node.right:
internal(node.right)
result.append(node.value)
internal(self.root)
return result
except AttributeError:
return []
def find_maximum_value(self):
try:
result = []
result.append(0)
def internal(node):
if node.value > result[0]:
result[0] = node.value
if node.left:
internal(node.left)
if node.right:
internal(node.right)
internal(self.root)
return result[0]
except AttributeError:
return []
def breadthFirst(self,result =[]):
try:
queue = Queue()
queue.enqueue(self.root)
while queue.front:
curr = queue.front
if curr.value.left:
queue.enqueue(curr.value.left)
if curr.value.right:
queue.enqueue(curr.value.right)
result.append(curr.value.value)
queue.dequeue()
return result
except AttributeError:
return 'Empty tree'
class BinarySearchTree(BinaryTree):
def add(self,value):
self.arr.append(value)
if self.root == None:
self.root=NodeTwo(value)
else:
def internal(node):
if value < node.value:
if node.left == None:
node.left = NodeTwo(value)
return
else:
internal(node.left)
else:
if node.right == None:
node.right = NodeTwo(value)
return
else:
internal(node.right)
internal(self.root)
def contains(self,value):
if value in self.arr:
return True
else:
return False
|
13943bc0b69d29a1ec34733febc67ad7f01d45e9 | sipspatidar/whatsapp_data_extractor | /remove_duplicate_and_sort.py | 436 | 3.703125 | 4 | import os
def list_Remove_Duplicates(x):
return sorted(set(x))
def Main():
os.chdir("links")
inputfn = input("enter the file name without extension : ")
po = open(inputfn+".txt","r")
line = "esf"
link = []
while(line!=""):
line = po.readline()
link.append(line)
result = sorted(set(link))
poa = open("new_"+inputfn+".txt",'w')
print("writing into file")
for w in result:
print(w)
poa.write(w)
|
f586b6e358a7ecc0219539285af09a4ac3d0ff33 | safkat33/Python-Sorting | /ProblemSolve/TwoSums.py | 1,033 | 3.953125 | 4 | from typing import List
"""
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
"""
class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
complement_map = dict()
length = len(nums)
for i in range(length):
num = nums[i]
complement = target - num
if num in complement_map:
return [complement_map[num], i]
else:
complement_map[complement] = i
@staticmethod
def brute_force_two_sum(nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(length):
for j in range(i + 1, length):
if i == j:
continue
elif nums[i] + nums[j] == target:
return [i, j]
|
d2b28cdd593f3a421083bc94fcec41723fe43279 | JohannesBuchner/pystrict3 | /tests/expect-fail23/recipe-576783.py | 2,694 | 3.71875 | 4 | # State Capitals Game
import random
def main():
state_capitals={"Washington":"Olympia","Oregon":"Salem",\
"California":"Sacramento","Ohio":"Columbus",\
"Nebraska":"Lincoln","Colorado":"Denver",\
"Michigan":"Lansing","Massachusetts":"Boston",\
"Florida":"Tallahassee","Texas":"Austin",\
"Oklahoma":"Oklahoma City","Hawaii":"Honolulu",\
"Alaska":"Juneau","Utah":"Salt Lake City",\
"New Mexico":"Santa Fe","North Dakota":"Bismarck",\
"South Dakota":"Pierre","West Virginia":"Charleston",\
"Virginia":"Richmond","New Jersey":"Trenton",\
"Minnesota":"Saint Paul","Illinois":"Springfield",\
"Indiana":"Indianapolis","Kentucky":"Frankfort",\
"Tennessee":"Nashville","Georgia":"Atlanta",\
"Alabama":"Montgomery","Mississippi":"Jackson",\
"North Carolina":"Raleigh","South Carolina":"Columbia",\
"Maine":"Augusta","Vermont":"Montpelier",\
"New Hampshire":"Concord","Connecticut":"Hartford",\
"Rhode Island":"Providence","Wyoming":"Cheyenne",\
"Montana":"Helena","Kansas":"Topeka",\
"Iowa":"Des Moines","Pennsylvania":"Harrisburg",\
"Maryland":"Annapolis","Missouri":"Jefferson City",\
"Arizona":"Phoenix","Nevada":"Carson City",\
"New York":"Albany","Wisconsin":"Madison",\
"Delaware":"Dover","Idaho":"Boise",\
"Arkansas":"Little Rock","Louisiana":"Baton Rouge"}
incorrect_answers=[]
print("Learn your state capitals!\n\n")
while len(state_capitals)>0:
choice=random.choice(list(state_capitals.keys()))
correct_answer=state_capitals.get(choice)
print("What is the capital city of",choice,"?")
answer=input("# ")
if answer.lower()==correct_answer.lower():
print("That's Correct!\n")
del state_capitals[choice]
else:
print("That's Incorrect.")
print("The correct answer is",correct_answer)
incorrect_answers.append(choice)
print("You missed",len(incorrect_answers),"states.\n")
if incorrect_answers:
print("here's the ones that you may want to brush up on:\n")
for each in incorrect_answers:
print(each)
else:
print("Perfect!")
response=""
while response!="n":
main()
response=input("\n\nPlay again?(y/n)\n# ")
|
e34c7a67ba5d39975e24df84d1dd069cf9cd4a91 | ElenaVasyltseva/Beetroot-Homework | /lesson_6/task_1.py | 1,003 | 3.984375 | 4 | # Task 1
# Make a program that has some sentence (a string) on input
# and returns a dict containing all unique words as keys
# and the number of occurrences as values.
while True:
user_text = input('Please, enter a text:').replace(',', ' ').replace('.', ' ').replace('!', ' ').replace('?', ' ')
user_text = user_text.replace('(', ' ').replace(')', ' ').replace('-', ' ').lower().split(' ')
words_count = {}
for word in user_text:
if word not in words_count:
if word == "":
continue
words_count[word] = 0
words_count[word] += 1
for key, value in words_count.items():
print(f'{key} --> {value} time')
question_continue = input('Do you want to check another sentence? Enter yes or no:')
if question_continue == 'yes':
continue
elif question_continue == 'no':
print('Finish')
break
else:
print('Incorrect input! Finish!!')
break
|
62d919185d19df039cc4f67b2f1f8a747fc77e14 | sunnyyeti/Leetcode-solutions | /56 Merge Intervals.py | 1,092 | 3.890625 | 4 | # Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
# Example 1:
# Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
# Input: intervals = [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] and [4,5] are considered overlapping.
# Constraints:
# 1 <= intervals.length <= 104
# intervals[i].length == 2
# 0 <= starti <= endi <= 104
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
ans = []
intervals.sort(key=lambda x : x[0])
start, end = intervals[0]
for i in range(1,len(intervals)):
if intervals[i][0] > end:
ans.append([start,end])
start,end = intervals[i]
else:
end = max(intervals[i][1],end)
ans.append([start,end])
return ans
|
726dfec7abfdab70fba752b76ca6823fdc3c1757 | Surapee/batavia | /testserver/code.py | 314 | 4.09375 | 4 |
class Point:
def __init__(self, firstPoint, secondPoint):
self.firstPoint = firstPoint
self.secondPoint = secondPoint
def distance(self):
return self.firstPoint ** self.firstPoint + self.secondPoint ** self.secondPoint
point = Point(2, 3)
print('Distance is', point.distance())
|
294c9db3d1b02af3e5ef9e9a5d6390ab24a64781 | Vanshika-RJIT/python-programs | /perfect square number.py | 120 | 3.65625 | 4 | import math
for i in range(1,501):
x=math.sqrt(i)
if(x==math.floor(x)):
print(i,end=' ')
|
e2f62108ce61c0d4a7b4c0b2372fbf88b92096ef | mohibul2000/MY_PROJECTS | /assignments.py/Q10.py | 151 | 4.3125 | 4 | # Tuples
"""
10. Write a Python program to reverse all the elements in a tuple without using the tuple
function.
"""
tp=(1,2,3,4)
print(tp[::-1]) |
4c51784ada56ce32ed511c64c36236b60f77a6a5 | NSLeung/Educational-Programs | /Python Scripts/test_script.py | 136 | 3.625 | 4 | import numpy as np
# print(np.exp(2))
x = [1, 2, 3, 4, 5, 6, 7]
y = np.zeros(2*len(x) - 1)
print("hello", x)
y[::2] = x
print(y)
|
682dc7e3b6a8782908224cd6968fa8bf48534b89 | AbdulkarimF/Python | /Day13.py | 842 | 4.59375 | 5 | # Python Lists
# create a List
print('Example 1')
s = []
print(s)
print('Example 2')
Numbers = [1, 2, 3, 4, 5]
print(Numbers)
print('Example 3')
thislist = ['apple', 'banana', 'cherry']
print(thislist)
print('Example 4')
thislist = ['apple', 'banana', 'cherry', 1, 2, 3]
print(thislist)
# Access Items
print('Example 5')
thislist = ['apple', 'banana', 'cherry']
print(thislist[-1])
# Loop Through a List
print('Example 6')
thislist = [1, 2, 2.0]
for x in thislist:
print(x)
# Change Item Value
print('Example 7')
thislist = ['apple', 'banana', 'cherry']
thislist[2]= 'orange'
print(thislist)
print('Example 8')
thislist = ['apple', 'banana', 'cherry']
del thislist[-1]
print(thislist)
print('Example 9')
thislist = ['apple', 'orange', 'cherry']
print('Error because there is not a list')
# del this list |
73a72cd68be817536ada156e1070f3fe3dfdf890 | AlphaGarden/LeetCodeProblems | /Easy/121_Best_Time_To_Buy_and_Sell_Stock.py | 1,034 | 3.890625 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
"""
import sys
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
ans = 0
min_buy = sys.maxint
for i in prices:
if i < min_buy:
min_buy = i
elif (i - min_buy) > ans:
ans = i - min_buy
return ans
if __name__ == '__main__':
test_case = [7, 6, 4, 3, 1]
test_case_2 = [7, 1, 5, 3, 6, 4]
solution = Solution()
print (solution.maxProfit(test_case_2)) |
78da8486dfa4e992c6f90b2c501c47aab40bf22d | rupesh7399/rupesh | /Rupesh/python/continue.py | 234 | 4.125 | 4 | while True:
n = int(input("Please enter an Integer: "))
if n < 0:
continue # this will take the execution back to the starting of the loop
elif n == 0:
break
print("Square is ", n ** 2)
print("Goodbye") |
9bdeb46faf365b5f60527029029b5cc90fa761f8 | rafaelperazzo/programacao-web | /moodledata/vpl_data/51/usersdata/128/19883/submittedfiles/listas.py | 446 | 3.765625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
def maiorDegrau(l):
maiorD=0
for i in range(0,(len(l)-1),1):
degrau=l[i]-l[i+1]
if degrau<0:
degrau=degrau*(-1)
if degrau>maiorD:
maiorD=degrau
return maiorD
n=input('Quantidade de termos: ')
lista=[]
for i in range (0,n,1):
lista.append(input('Digite um termo: '))
print maiorDegrau(lista) |
8d4d046b5e48a5fffac4fd596b063b9942a29259 | tathagata218/All-Projects | /Algorithms/Selection Sort/sort.py | 300 | 3.6875 | 4 | a = [6,43,32,1,23,4,8,7]
def selectionSort (a):
for i in range(0,len(a)):
testValue = a[i]
for x in range(i+1,len(a)):
if(testValue > a[x]):
testValue = a[x]
a[x] = a[i]
a[i] = testValue
print(a)
selectionSort(a) |
e3d64ad8c6ef798f5b08068d200ca708b3d1d36d | Raiugami/Exercicios_Python-n2 | /exe065.py | 539 | 3.9375 | 4 | cont = media = maior = menor = 0
resp = 'S'
while resp == 'S':
num = int(input("Informe um numero: "))
media = media + num
cont += 1
if cont == 1:
menor = maior = num
else:
if num > maior:
maior = num
if num < menor:
menor = num
resp = str(input("Deseja continuar? [S] ou [N] ")).upper().strip()
media = media / cont
print(f"O maior numero digitado foi {maior}")
print(f"O menor numero digitado foi {menor}")
print(f"A média é igual á: {media}")
|
f727ee2d5e1894a22cfc8cef79514faf19aacbcf | duochen/Python-Beginner | /Lecture05/Labs/user.py | 1,041 | 3.828125 | 4 | class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print(self.first_name, self.last_name)
def greet_user(self):
print("Hello " + self.first_name + "," + self.last_name)
user1 = User("Duo", "Chen")
user2 = User("Jie", "Lin")
user1.describe_user()
user1.greet_user()
user2.describe_user()
user2.greet_user()
class Admin(User):
def __init__(self, first_name, last_name, privileges):
super(Admin, self).__init__(first_name, last_name)
self.privileges = privileges
def show_privileges(self):
self.privileges.show_privileges()
class Privileges:
def __init__(self, privileges):
self.privileges = privileges
def show_privileges(self):
for privilege in self.privileges:
print(privilege)
privileges = Privileges(["can add post", "can delete post"])
admin = Admin("Lillian", "Chen", privileges )
admin.show_privileges() |
db193f6cb88fe7a741fc6ea574d799076f2d0bf1 | LeeSangYooon/Gomoku_AI | /game/Game.py | 1,583 | 3.609375 | 4 | from game.Board import Board
class Game:
def __init__(self):
self.board = Board()
self.turn = 1
self.result = 0
def move(self, pos):
self.board.board[pos[1]][pos[0]] = self.turn
self.result = self.get_result(pos)
self.turn = 3 - self.turn
def get_result(self, pos):
x = pos[0]
y = pos[1]
row = 0
for i in range(self.board.size[0]):
if self.board.board[y][i] == self.turn:
row += 1
if row == 5:
return self.turn
else:
row = 0
row = 0
for i in range(self.board.size[1]):
if self.board.board[i][x] == self.turn:
row += 1
if row == 5:
return self.turn
else:
row = 0
row = 0
min_pos = min(x, y)
i = y - min_pos
j = x - min_pos
while j<self.board.size[0] and i<self.board.size[1]:
if self.board.board[i][j] == self.turn:
row += 1
if row == 5:
return self.turn
else:
row = 0
i+=1
j+=1
i = y - min_pos
j = self.board.size[0] - x + min_pos - 1
while j>=0 and i<self.board.size[1]:
if self.board.board[i][j] == self.turn:
row += 1
if row == 5:
return self.turn
else:
row = 0
i+=1
j-=1
return 0 |
1a2ac4656d8e27d5f1f6ab802a18257ab1347737 | Tuhgtuhgtuhg/PythonLabs | /lab05/lab5_1.py | 1,601 | 4.03125 | 4 | class Book:
def __init__(self, name = " ", year = 0, genre = " "):
if name != " " and 0<year<=2021 and genre != " ":
self.name = name
self.genre = genre
self.year = year
else:
print("Помилка додавання книги!")
class Lib:
def __init__(self):
self.library = []
def addBook(self, Book):
if Book not in self.library:
self.library.append(Book)
print("Книга " + str(Book.name) + " була успішно доданa до бібліотеки")
def findBook(self, info):
for search in self.library:
if search.name == info or search.year == info or search.genre == info:
print("Книга знайдена!")
print("Назва: "+str(search.name) + "\nРік: " + str(search.year) + "\nЖанр: " + str(search.genre))
break
else:
print("Книгу не вдаєтся знайти...")
def delBook(self, b):
for search in self.library:
if b is search:
self.library.remove(b)
print("Книгу успішно видалено.")
if __name__ == '__main__':
library = Lib()
name = input("Введіть назву книги: ")
year = int(input("Введіть рік редакції книги: "))
genre = input("Введіть жанр книги: ")
book = Book(name, year, genre)
library.addBook(book)
library.findBook(name)
library.delBook(book)
library.findBook(name)
|
641e13220384ed9502d098559c8a90fed267d7e0 | Lucas-Guimaraes/Reddit-Daily-Programmer | /Easy Problems/21-30/21easy.py | 361 | 4.15625 | 4 | #https://www.reddit.com/r/dailyprogrammer/comments/qp3ub/392012_challenge_21_easy/
def higher_num(num):
count = num+1
while True:
if str(num) in str(count):
False
return count
else:
count = count+1
num_test = int(raw_input("Put in a number!: "))
print higher_num(num_test)
raw_input() |
cf374ba41e7638727c8762e294e0210ea2af87b2 | Skylow369/Matrix-Operations | /MatrixClass.py | 5,415 | 3.765625 | 4 | import copy
import random
class Matrix:
def __init__(self, matrix=None, numrows=0, numcols=0):
self.numrows = numrows
self.numcols = numcols
self.rows = []
self.columns = []
self.setvals(matrix)
def printmatrix(self):
print("Matrix:")
for i in self.rows:
print(i)
print("")
def setvals(self, mat=None):
if mat is None:
if self.numrows == 0 and self.numcols == 0:
self.numrows = int(input("Number of rows: "))
self.numcols = int(input("Number of columns: "))
print("\nSeparate numbers by one space and round decimals to the nearest thousandth")
for i in range(self.numrows):
vals = input("Row " + str(i+1) + ": ")
row = list(map(float, vals.split(' ')))
if len(row) != self.numcols:
print("Incorrect number of values")
return
self.rows.append(row)
else:
self.rows = mat
self.numrows = len(mat)
self.numcols = len(mat[0])
for i in range(self.numcols):
self.columns.append([])
for i in range(len(self.rows)):
for x in range(len(self.rows[0])):
self.columns[x].append(self.rows[i][x])
print("")
def inverse(self):
mat = copy.deepcopy(self.columns)
if len(mat) != len(mat[0]):
print("Matrix needs to be a square matrix\n")
return
d = self.determinant(mat)
if len(mat) == 2 and len(mat[0]) == 2:
mat = copy.deepcopy(self.rows)
mat[0][0], mat[1][1] = mat[1][1], mat[0][0]
mat[0][1] *= -1
mat[1][0] *= -1
for i in range(len(mat)):
for x in range(len(mat[0])):
mat[i][x] *= (1/d)
mat[i][x] = round(mat[i][x], 3)
mat = Matrix(mat)
return mat
inmat = copy.deepcopy(mat)
for i in range(len(mat)):
for x in range(len(mat[0])):
minor = self.minor(i, x, mat)
inmat[i][x] = ((-1)**(i + x)) * self.determinant(minor)
inmat[i][x] *= (1/d)
inmat[i][x] = round(inmat[i][x], 3)
inmat = Matrix(inmat)
return inmat
def minor(self, row, column, matrix):
minor = copy.deepcopy(matrix)
minor.pop(row)
for i in range(len(minor)):
minor[i].pop(column)
return minor
def determinant(self, mat=None):
if mat is None:
mat = self.rows
if len(mat) == 2 and len(mat[0]) == 2:
return (mat[0][0]*mat[1][1]) - (mat[0][1]*mat[1][0])
if len(mat) != len(mat[0]):
print("Matrix needs to be a square matrix\n")
return
determinant = 0
for i in range(len(mat[0])):
minor = copy.deepcopy(mat)
minor = self.minor(0, i, minor)
if i % 2 == 0:
determinant += mat[0][i] * self.determinant(minor)
else:
determinant -= mat[0][i] * self.determinant(minor)
return determinant
def __add__(self, other):
if self.numrows != other.numrows or self.numcols != other.numcols:
print("Cannot add matrices\n")
return
newmat = []
for i in range(self.numrows):
newmat.append([])
for x in range(self.numcols):
newmat[i].append(self.rows[i][x] + other.rows[i][x])
newmat = Matrix(newmat)
return newmat
def __sub__(self, other):
if self.numrows != other.numrows or self.numcols != other.numcols:
print("Cannot subtract matrices\n")
return
newmat = []
for i in range(self.numrows):
newmat.append([])
for x in range(self.numcols):
newmat[i].append(self.rows[i][x] - other.rows[i][x])
newmat = Matrix(newmat)
return newmat
def __mul__(self, other):
if type(other) == int:
for i in range(self.numrows):
for x in range(self.numcols):
self.rows[i][x] *= other
for i in range(len(self.columns)):
for x in range(len(self.columns[0])):
self.columns[i][x] *= other
self.printmatrix()
return
if type(other) == Matrix:
if len(self.columns) != len(other.rows):
print("Cannot multiply matrices\n")
return
newmat = []
for i in range(self.numrows):
newmat.append([])
count = 0
sum = 0
for row in range(self.numrows):
for col in range(other.numcols):
while count < self.numcols:
sum += self.rows[row][count] * other.columns[col][count]
count += 1
newmat[row].append(round(sum, 3))
sum = 0
count = 0
newmat = Matrix(newmat)
return newmat
|
8ea103c88ebfdc8947a8236fa1f00c86341c385e | sukmin-ddabong/megait_python_20201020 | /03_loop/quiz02/quiz02_3.py | 237 | 3.703125 | 4 | for i in range(1, 51): # 1 ~ 50, 1씩 증가
if i % 3 == 0: # i를 3으로 나누어 떨어지면 3의 배수
print(i, end=" ")
# 다른 방법
for i in range(3, 51, 3): # 3 ~ 50, 3씩 증가
print(i, end=" ")
|
96e8e30db9b28b4da52b771030578e3c0fae4f43 | jparng/Guess_Num | /GuessNum.py | 365 | 4.0625 | 4 | import random
x = random.randrange(1,20)
y = int(input('Choose a number between 1 and 20 '))
while y != x:
if y > x:
print('Too high. Try again')
y = int(input('Choose a number between 1 and 20 '))
else:
print('Too low. Try again.')
y = int(input('Choose a number between 1 and 20 '))
print('Correct! You win!')
|
9d39e2403c8f08b561a0665eed2e64767d822b94 | pravinmaske/TorontoPython | /indices_over_two_objects.py | 842 | 3.90625 | 4 | def count_matches(s1,s2):
"""
Return the number of positions in s1 that contains the same character
at the corresponding position of s2.
Precondition: len(s1) == len(s2)
>>>count_matches('ate','ape')
2
>>>count_matches('head','hard')
2
"""
count_match=0
for i in range(len(s1)):
if s1[i] == s2[i]:
count_match+=1
return count_match
def sum_items(list1,list2):
"""
(list of number, list of number) -> list of number
Return a new list in which each item is the sum of the items at
the corrosponding position of list1 and list2
>>>sum_items([1,2,3],[2,4,5])
[3,6,8]
>>>sum_items([2,3,1],[3,2,1])
[5,5,2]
"""
sum_items=[]
for i in range(len(list1)):
#sum_items[i]=list1[i]+list2[i]
sum_items.append(list1[i]+list2[i])
return sum_items
print(sum_items([1,2,3],[2,4,5]))
print(count_matches('headi','hardi')) |
3b0ab4a6cdf808cb9661b728581e4593b4503673 | ValentynaGorbachenko/cd2 | /ltcd/moveZeroes.py | 604 | 4.09375 | 4 | '''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
'''
def moveZeroes(nums):
cnt = nums.count(0)
nums.extend([0]*cnt)
print(nums)
j=0
for i in range(len(nums)-cnt):
i+=j
print(i, nums[i])
if nums[i] == 0:
nums.pop(i)
j-=1
print(nums)
moveZeroes([0,0,0,0,1,0,3,12])
|
577767a7554a67aeb99dcec9cfbe577a506ed9b6 | parag2005/acadgild_Hyd_Assignments | /Python Assignment/Problem_Statement1_Python2_5_2.py | 913 | 3.734375 | 4 | from pip._vendor.distlib.compat import raw_input
subjects_of_sentence = raw_input('Please enter a set of words to define the subject words ? ')
""" The first set of words includes ["American","Indians"] """
verbs_of_sentence = raw_input('Please enter a set of words to define the verb words ? ')
""" The second set of words includes ["play","watch"] """
objects_of_sentence = raw_input('Please enter a set of words to define the object words of sentence ? ')
""" The third set of words include ["Baseball","Cricket"] """
list1 = list(subjects_of_sentence.split())
list2 = list(verbs_of_sentence.split())
list3 = list(objects_of_sentence.split())
separator = " "
for subject_index in range(0,len(list1)):
for verb_index in range(0,len(list2)):
for object_index in range(0,len(list3)):
print(list1[subject_index]+ separator + list2[verb_index]+ separator +list3[object_index])
|
88002c182c9e8adea863cc44bf816dba504241ab | supermavster/Platzi-Master-Python | /2-basics/25-listComprehension.py | 1,264 | 4.09375 | 4 | # Secuencia existente en una nueva existencia
# Dictionary comprehension - list comprehension
# Dictionary comprehension y list comprehension nos permite
# escribir listas o diccionarios de forma más sencilla.
## LISTAS
# Números pares
pares = []
for num in range(1,31):
if num % 2 == 0:
pares.append(num)
# Esto mismo lo podemos expresar con una list comprehension
print(pares)
# numero de la variable generada numero del rango (del 1 al 30) donde si esta variable generada numero es divisible (par)
pares = [num for num in range(1,31) if num % 2 == 0]
print(pares)
## Diccionarios
cuadrados = {}
for num in range(1, 11):
cuadrados[num] = num ** 2
print(cuadrados)
cuadrados = {num: num ** 2 for num in range(1, 11)}
print(cuadrados)
# En informática, el azúcar sintáctico es un término acuñado por Peter J. Landin en 1964 para referirse a los añadidos a la sintaxis de un lenguaje de programación diseñados para hacer algunas construcciones más fáciles de leer o expresar. Esto hace el lenguaje “más dulce” para el uso por programadores: las cosas pueden ser expresadas de una manera más clara, más concisas, o de un modo alternativo que se prefiera, sin afectar a la funcionalidad del programa. |
e71baf43131650cd2eed7a9087eab5ba1061d15a | evamwangi/Andela_bootcamp_vii | /day_3/args_kwargs.py | 1,055 | 4.09375 | 4 | #unpacking
def hallo(name, age, class_=""):
"""
explanation on what it does
"""
if class_ != "":
return "i am {}, and i am {}, and {} class".format(name, age, class_)
return "i am {}, and i am {}".format(name,age)
people = [
("jane",23,'high'),
("joe" , 25,'low'),
("brian", 60),
("betty", 45)
]
'''
for name, age, class_ in people:
print hallo(name,age, class_)
'''
#use of unpacking
for person in people:
print hallo(*person)
def super_sum(*args):
"""
takes in variable number of items
and returns the sum.
e.g. super_sum(10,20)=30
super_sum(10,20,30)=70
"""
total = 0
for i in args:
total += i
return total
print super_sum(10, 20)
print super_sum(1,4,5,7)
a = [10,40,60]
print super_sum(*a)
b = {1:"hallo",2:"me"}
print super_sum(*b)
def hello_again(**kwargs):
return "i am {}, and i am {}".format(kwargs['name'],kwargs['age'])
print hello_again(name='Joe', age=20)
print hello_again(age=20, name='jane')
joe={'name': 'joe', 'age':98}
print hello_again(**joe)
print hello_again(name='joe',age=98)
|
af221caf598132140302174b1bf827cad528f221 | kvswim/kv_jhu_cv | /HW2/ssift_descriptor.py | 750 | 3.625 | 4 | import cv2
import numpy
import matplotlib.pyplot as plt
def ssift_descriptor(feature_coords,image):
"""
DO NOT DO - not required for 461
Computer Vision 600.461/661 Assignment 2
Args:
feature_coords (list of tuples): list of (row,col) tuple feature coordinates from image
image (numpy.ndarray): The input image to compute ssift descriptors on. Note: this is NOT the image name or image path.
Returns:
descriptors (dictionary{(row,col): 128 dimensional list}): the keys are the feature coordinates (row,col) tuple and
the values are the 128 dimensional ssift feature descriptors.
"""
descriptors = dict()
return descriptors
|
1cf8c07e53d1d97a0cad05e3a888647df33b5b23 | DrRuisseau/fp_train | /python/lec4/main/Reduce.py | 170 | 3.671875 | 4 | product = 1
x = [1, 2, 3, 4]
for num in x:
product = product * num
from functools import reduce
product = reduce((lambda x, y: x * y),[1, 2, 3, 4])
print(product)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.