blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
a47e31222de348822fbde57861341ea68a4fa5fb | Ph0tonic/TP2_IA | /connection.py | 927 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Connection:
"""
Class connection which allow to link two cities, contains the length of this connection
"""
def __init__(self, city1, city2, distance):
""" Constructor
:param city1: City n°1
:param city2: City n°2
:param distance: distance between the 2 cities
"""
self.city1 = city1
self.city2 = city2
self.distance = distance
def get_linked(self, city):
""" get the other city connected via this connection
:param city: city from where the connection is coming from
:return: city where the connection is going
"""
return self.city1 if city != self.city1 else self.city2
def __str__(self):
"""
To String function for debug
"""
return str(self.city1)+" - "+str(self.city2) |
4f87bbe6f76985ef685e27c875d07c606c2c70ee | Sairam-Yeluri/DCA | /Inbuild Functions/Strings/isupper().py | 108 | 3.96875 | 4 | str1 = 'SAIRAM'
str2 = 'SAI RAM'
str3 = 'sAI RAM' #F
print(str1.isupper(),str2.isupper(),str3.isupper()) |
2a0983a97e80de6a050a0c93b7605268058a6ccc | Sairam-Yeluri/DCA | /Min and Max in list.py | 236 | 3.9375 | 4 | lst = [5,20,-6,-4,1,3]
temp1 = lst[0]
for i in lst:
if i < temp1:
temp1 = i
temp2 = lst[0]
for j in lst:
if j > temp2:
temp2 = j
print("Smallest number is {} and Largest number is {}".format(temp1,temp2))
|
e32186f4565cac5b1d451a3363503ec9c41b5cd9 | Sairam-Yeluri/DCA | /IMP/Armstrong Number.py | 158 | 3.546875 | 4 | n = int(input("Enter Number: ")) #153 , 154
lst = list(str(n))
k = 0
for i in lst:
k = k+pow(int(i),3)
if k == n:
print("Yes")
else:
print("No")
|
c9cbf5e1efbad21468e3d78508e7da1151ed122b | reillydj/ProjectEuler | /problem_seven.py | 797 | 3.90625 | 4 | __author__ = "David Reilly"
"""
Project Euler
Problem: 7
'By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?'
"""
import math
def is_prime(integer):
if integer == 2:
return True
for candidate in xrange(2, int(math.ceil(integer ** 0.5)) + 1):
if integer % float(candidate) == 0:
return False
return True
def generate_primes(nth_prime):
index = 1
number = 2
while index <= nth_prime:
print number, is_prime(number), index
if is_prime(number):
index += 1
number += 1
else:
number += 1
return number
if __name__ == "__main__":
prime = generate_primes(10001)
print prime
|
67e085ffc5b6c37dda9edf27a527cb5e79980f96 | wawiesel/BootsOnTheGround | /external/TriBITS/common_tools/test/hhmmss_math.py | 4,153 | 3.890625 | 4 | #!/usr/bin/env python
#
# This simple set of python functions makes it easy to do simple math with
# times formatted as <hr>h<min>m<sec>s. This makes it easier to analyze
# timing data that is spit out in that form.
#
import sys
import os
def hms2s(hms):
#print "mmss =", mmss
hms_len = len(hms)
h_idx = hms.find("h")
m_idx = hms.find("m")
s_idx = hms.find("s")
# hours
hours = 0.0
if h_idx > 0:
h_start = 0
hours = float(hms[0:h_idx])
# ToDo: Handle 'm' and 's'
# minutes
minutes = 0.0
if m_idx > 0:
m_start = 0
if h_idx > 0:
m_start = h_idx + 1
minutes = float(hms[m_start:m_idx])
# seconds
seconds = 0.0
if s_idx > 0:
s_start = 0
if m_idx > 0:
s_start = m_idx + 1
elif h_idx > 0:
s_start = h_idx + 1
seconds = float(hms[s_start:s_idx])
return hours*3600 + minutes*60 + seconds
def s2hms(seconds):
s_digits = 5
#print ""
#print "seconds =", seconds
hours = int(seconds) / 3600
#print "hours =", hours
seconds_h_remainder = round(seconds - hours*3600, s_digits)
#print "seconds_h_remainder =", seconds_h_remainder
minutes = int(seconds_h_remainder) / 60
#print "mintues =", minutes
seconds_reminder = round(seconds_h_remainder - minutes*60, s_digits)
#print "seconds_reminder = ", seconds_reminder
h_str = ""
if hours != 0:
h_str = str(hours)+"h"
m_str = ""
if minutes != 0:
m_str = str(minutes)+"m"
s_str = ""
if seconds_reminder != 0.0:
s_str = str(seconds_reminder)+"s"
return h_str + m_str + s_str
def sub_hms(hms1, hms2):
num1 = hms2s(hms1)
num2 = hms2s(hms2)
return s2hms(num1 - num2)
def div_hms(hms_num, hms_denom):
num_num = hms2s(hms_num)
num_denom = hms2s(hms_denom)
return num_num/num_denom
#
# Unit test suite
#
if __name__ == '__main__':
import unittest
class test_hms2s(unittest.TestCase):
def setUp(self):
None
def test_s1(self):
self.assertEqual(hms2s("2s"), 2.0)
def test_s2(self):
self.assertEqual(hms2s("2.53s"), 2.53)
def test_s3(self):
self.assertEqual(hms2s("0m4.5s"), 4.5)
def test_m1(self):
self.assertEqual(hms2s("1m2.4s"), 62.4)
def test_m2(self):
self.assertEqual(hms2s("3m10.531s"), 190.531)
def test_h1(self):
self.assertEqual(hms2s("2h"), 7200.0)
def test_h1(self):
self.assertEqual(hms2s("2.5h"), 9000.0)
def test_h2(self):
self.assertEqual(hms2s("1h2m3s"), 3723.0)
def test_h3(self):
self.assertEqual(hms2s("1h3s"), 3603.0)
class test_s2hms(unittest.TestCase):
def setUp(self):
None
def test_s1(self):
self.assertEqual(s2hms(2.0), "2.0s")
def test_s2(self):
self.assertEqual(s2hms(3.456), "3.456s")
def test_s3(self):
self.assertEqual(s2hms(60.0), "1m")
def test_m1(self):
self.assertEqual(s2hms(75.346), "1m15.346s")
def test_m2(self):
self.assertEqual(s2hms(121.25), "2m1.25s")
def test_m3(self):
self.assertEqual(s2hms(60.0), "1m")
def test_h1(self):
self.assertEqual(s2hms(3600.0), "1h")
def test_h2(self):
self.assertEqual(s2hms(3600.001), "1h0.001s")
def test_h3(self):
self.assertEqual(s2hms(3660.0), "1h1m")
def test_h4(self):
self.assertEqual(s2hms(7140.0), "1h59m")
def test_h5(self):
self.assertEqual(s2hms(7141.0), "1h59m1.0s")
def test_h5(self):
self.assertEqual(s2hms(2*3600+3*60+7.82), "2h3m7.82s")
class test_sub_hms(unittest.TestCase):
def setUp(self):
None
def test_1(self):
self.assertEqual(sub_hms("2s", "1s"), "1.0s")
def test_2(self):
self.assertEqual(sub_hms("1m5.23s", "45s"), "20.23s")
class test_div_hms(unittest.TestCase):
def setUp(self):
None
def test_1(self):
self.assertEqual(div_hms("2s", "1s"), 2.0)
def test_2(self):
self.assertEqual(div_hms("1s", "2s"), 0.5)
def test_3(self):
self.assertEqual(div_hms("1m50s", "55s"), 2.0)
def test_4(self):
self.assertEqual(div_hms("55s", "1m50s"), 0.5)
unittest.main()
|
238fda6498cb428fc796671fa6e34beb6bd9f1a6 | wuziwei1994/project_learn | /api/task/Task_007/animalGame.py | 1,782 | 3.625 | 4 | from random import randint
import time
class Tiger:
animalName = '老虎'
def __init__(self,weight):
self.weight = weight
def call(self):
print('WOW !!,体重减少5')
self.weight -= 5
def eat(self,food):
if food == 'meat':
self.weight += 10
print('喂食正确,体重增加10')
else:
self.weight -= 10
print('喂食错误,体重减少10')
class Sheep:
animalName = '羊'
def __init__(self,weight):
self.weight = weight
def call(self):
print('mie~~~,体重减少5')
self.weight -= 5
def eat(self,food):
if food == 'grass':
self.weight += 10
print('喂食正确,体重增加10')
else:
self.weight -= 10
print('喂食错误,体重减少10')
class Room:
def __init__(self,num,inanimal):
self.num = num
self.animal = inanimal
rooms = []
for i in range(2,12):#循环创建10个房间实例,根据随机数添加每个房间的动物实例
if randint(0,1) == 1:
ani = Tiger(200)
else:
ani = Sheep(100)
room = Room(i,ani)
rooms.append(room)
startTimes = time.time()
while True:#当前减去开始时间大于120秒结束循环
nowTimes = time.time()
roomNum = randint(1, 10)
if (nowTimes - startTimes ) > 120:
print('游戏结束')
for idx, room in enumerate(rooms):
print(f'{idx+1:},{room.animal.animalName:},{room.animal.weight:}')
break
hit = input(f'当前房间号是:{roomNum:},请问是否敲门:1 or 2 : ')
if hit == '1':
room.animal.call()
eatFood = str(input("请选择喂食食物:'meat' or 'grass' : "))
room.animal.eat(eatFood)
|
f8bc0b4541d4569cb5f54b8d6397f343370da5aa | wuziwei1994/project_learn | /api/task/Task_004/mySort.py | 175 | 3.78125 | 4 | def mySort(List):
newList=[]
for i in range(len(List)):
newList.append(min(List))
List.remove(min(List))
return newList
print(mySort([1,0,2,5,7]))
|
052e2989a10ab674395e4a11ecab1e2560109af4 | charlenellll/LeetCodeSolution | /61 Rotate List/rotateRight.py | 1,148 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None or k == 0:
return head
dummyHead = ListNode(0)
dummyHead.next = head
p = dummyHead
q = p
# I don't know why for-loop like in C++ or Java would meet Memory Error here, eventually while-loop works
length = 0
while length < k:
q = q.next
length += 1
if q.next == None:
break
if q.next == None:
k = k % length
q = p
for i in range(0,k):
q = q.next
while q.next != None:
p = p.next
q = q.next
q.next = dummyHead.next
dummyHead.next = p.next
p.next = None
retNode = dummyHead.next
del dummyHead
return retNode |
319aeabc01e1be75da2f1ecee9129c360a5414b1 | KNTU-Algorithm-Design-Spring-2021/individual-project-3-sadeghi-aa | /Code/main.py | 1,105 | 3.765625 | 4 | def parse(sentence, previous=None):
if not previous:
sentence = sentence.lower()
if sentence is '':
return previous
else:
length = len(sentence)
for i in list(range(2, length + 1)) + [1]:
nextWord = sentence[0:i]
if nextWord in wordSet:
remSentence = sentence[i:]
found = parse(remSentence, nextWord)
if found:
if previous:
return f"{previous} {found}"
else:
return f"{found}"
if not previous:
return "This sentence can't be parsed :("
f = open('The_Oxford_3000.txt', 'r')
wordSet = set([s.lower() for s in f.read().split()])
if __name__ == '__main__':
sentence = "IHOPETHISISOURLASTPROJECTINTHISCOURSE"
print(parse(sentence))
sentence = 'WEAREVERYTIREDRIGHTNOW'
print(parse(sentence))
sentence = 'SLEEPISINTHEDICTIONARY'
print(parse(sentence))
sentence = 'SLEEPYISNOTINTHEDICTIONARY' # Sleepy is not in the dictionary
print(parse(sentence))
|
c2b6d92e28284d84dfc525b3bf5f9c33596f46ad | LokeshKD/DSPython | /stk/dec_to_num.py | 265 | 3.875 | 4 | from stack import Stack
def convert_int_to_bin(dec_num):
rem = Stack()
bin_num = ""
while dec_num > 0:
rem.push(dec_num % 2)
dec_num //= 2
while not rem.is_empty():
bin_num += str(rem.pop())
return bin_num
print(convert_int_to_bin(4))
|
01898fb8344e604758c78eeda505f7638b7aa911 | Rybalchenko4/homework_func | /homework_func.py | 2,264 | 3.5 | 4 | documents = [
{"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"},
{"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"},
{"type": "insurance", "number": "10006", "name": "Аристарх Павлов"}
]
directories = {
'1': ['2207 876234', '11-2'],
'2': ['10006'],
'3': []
}
def get_name():
number = input('Введите номер документа: ')
for data in documents:
if data.get("number") == number:
return data.get('name')
return 'Документа с таким номером нет!'
def get_shelf():
number = input('Введите номер документа: ')
for key in directories :
if number in directories.get(key):
return key
return 'В полках документа с данным номером нет!'
def get_list(docs):
for doc in docs:
print(doc['type'], doc['number'], doc['name'])
def add_doc(doc_type, doc_number, doc_name, shelf_id):
if shelf_id not in directories:
return "Полки не существует!"
new_doc = dict(type=doc_type, number=doc_number, name=doc_name)
documents.append(new_doc)
directories[shelf_id] += [doc_number]
return "Документ успешно добавлен!"
HELP = '''
p/people - имя владельца по номеру документа,
s/shelf - номер полки по номеру документа,
l/list - список всех документов,
a/add - добавить новый документ,
q/quit - выход.
'''
while True:
print(HELP)
command = input('Введите название команды: ')
if command == 'p':
print(get_name())
elif command == 's':
print(get_shelf())
elif command == 'l':
print(get_list(documents))
elif command == 'a':
doc_type = input("Введите тип докемента: ")
doc_number = input("Введите номер документа: ")
doc_name = input("Введите имя владельца документа: ")
shelf_id = input("Введит номер полки: ".format(directories.keys()))
print(add_doc(doc_type, doc_number, doc_name, shelf_id))
elif command == 'q':
break
else:
print('Неверная команда!') |
7c0908716adc48d86db77b8cb630243d5a6c2772 | dbirman/cs375 | /assignment2/autoencoder_pooled_bottleneck_imagenet.py | 12,214 | 3.671875 | 4 | """
Welcome to the second part of the assignment 1! In this section, we will learn
how to analyze our trained model and evaluate its performance on predicting
neural data.
Mainly, you will first learn how to load your trained model from the database
and then how to use tfutils to evaluate your model on neural data using dldata.
The evaluation will be performed using the 'agg_func' in 'validation_params',
which operates on the aggregated validation results obtained from running the
model on the stimulus images. So let's get started!
Note: Although you will only have to edit a small fraction of the code at the
beginning of the assignment by filling in the blank spaces, you will need to
build on the completed starter code to fully complete the assignment,
We expect that you familiarize yourself with the codebase and learn how to
setup your own experiments taking the assignments as a basis. This code does
not cover all parts of the assignment and only provides a starting point. To
fully complete the assignment significant changes have to be made and new
functions need to be added after filling in the blanks. Also, for your projects
we won't give out any code and you will have to use what you have learned from
your assignments. So please always carefully read through the entire code and
try to understand it. If you have any questions about the code structure,
we will be happy to answer it.
Attention: All sections that need to be changed to complete the starter code
are marked with EDIT!
"""
from __future__ import division
import os
import numpy as np
import tensorflow as tf
import tabular as tb
import itertools
from scipy.stats import pearsonr, spearmanr
from dldata.metrics.utils import compute_metric_base
from tfutils import base, data, model, optimizer, utils
from dataprovider import ImageNetDataProvider
from pooledBottleneck_model import pBottleneck_model, pbottle_loss
class ImageNetClassificationExperiment():
"""
Defines the neural data testing experiment
"""
class Config():
"""
Holds model hyperparams and data information.
The config class is used to store various hyperparameters and dataset
information parameters. You will need to change the target layers,
exp_id, and might have to modify 'conv1_kernel' to the name of your
first layer, once you start working with different models. Set the seed
number to your group number. But please do not change the rest.
You will have to EDIT this part. Please set your exp_id here.
"""
target_layers=[ 'deconv2']
extraction_step = None
exp_id = '1st_experiment'
data_path = '/datasets/TFRecord_Imagenet_standard'
batch_size = 50
seed = 5
crop_size = 24
gfs_targets = []
extraction_targets = target_layers + ['labels']
assert ImageNetDataProvider.N_VAL % batch_size == 0, \
('number of examples not divisible by batch size!')
val_steps = int(ImageNetDataProvider.N_VAL / batch_size)
def __init__(self):
self.feature_masks = {}
def setup_params(self):
"""
This function illustrates how to setup up the parameters for train_from_params
"""
params = {}
"""
validation_params similar to train_params defines the validation parameters.
It has the same arguments as train_params and additionally
agg_func: function that aggregates the validation results across batches,
e.g. to calculate the mean of across batch losses
online_agg_func: function that aggregates the validation results across
batches in an online manner, e.g. to calculate the RUNNING mean across
batch losses
Note: Note how we switched the data provider from the ImageNetDataProvider
to the NeuralDataProvider since we are now working with the neural data.
"""
params['validation_params'] = {
'imagenet': {
'data_params': {
# ImageNet data provider arguments
'func': ImageNetDataProvider,
'data_path': self.Config.data_path,
'group': 'val',
'crop_size': self.Config.crop_size,
# TFRecords (super class) data provider arguments
'file_pattern': 'validation*.tfrecords',
'batch_size': self.Config.batch_size,
'shuffle': False,
'shuffle_seed': self.Config.seed,
'file_grab_func': self.subselect_tfrecords,
'n_threads': 4,
},
'queue_params': {
'queue_type': 'fifo',
'batch_size': self.Config.batch_size,
'seed': self.Config.seed,
'capacity': self.Config.batch_size * 10,
'min_after_dequeue': self.Config.batch_size * 5,
},
'targets': {
'func': self.return_outputs,
'targets': self.Config.extraction_targets,
},
'num_steps': self.Config.val_steps,
'agg_func': self.imagenet_classification,
'online_agg_func': self.online_agg,
}
}
"""
model_params defines the model i.e. the architecture that
takes the output of the data provider as input and outputs
the prediction of the model.
You will need to EDIT this part. Switch out the model 'func' as
needed when running experiments on different models. The default
is set to the alexnet model you implemented in the first part of the
assignment.
"""
params['model_params'] = {
'func': pBottleneck_model,
}
"""
save_params defines how, where and when your training results are saved
in the database.
You will need to EDIT this part. Set your own 'host' ('localhost' if local,
mongodb IP if remote mongodb), 'port', 'dbname', and 'collname' if you want
to evaluate on a different model than the pretrained alexnet model.
'exp_id' has to be set in Config.
"""
params['save_params'] = {
'host': '35.199.154.71',
'port': 24444,
'dbname': 'assignment2',
'collname': 'pooled_bottleneck',
'exp_id': self.Config.exp_id,
'save_to_gfs': self.Config.gfs_targets,
}
"""
load_params defines how and if a model should be restored from the database.
You will need to EDIT this part. Set your own 'host' ('localhost' if local,
mongodb IP if remote mongodb), 'port', 'dbname', and 'collname' if you want
to evaluate on a different model than the pretrained alexnet model.
'exp_id' has to be set in Config.
"""
params['load_params'] = {
'host': '35.199.154.71',
'port': 24444,
'dbname': 'assignment2',
'collname': 'pooled_bottleneck',
'exp_id': self.Config.exp_id,
'do_restore': True,
'query': {'step': self.Config.extraction_step} \
if self.Config.extraction_step is not None else None,
}
params['inter_op_parallelism_threads'] = 500
return params
def return_outputs(self, inputs, outputs, targets, **kwargs):
"""
Illustrates how to extract desired targets from the model
"""
retval = {}
for target in targets:
retval[target] = outputs[target]
return retval
def online_agg(self, agg_res, res, step):
"""
Appends the value for each key
"""
if agg_res is None:
agg_res = {k: [] for k in res}
# Generate the feature masks
for k, v in res.items():
if k in self.Config.target_layers:
num_feats = np.product(v.shape[1:])
mask = np.random.RandomState(0).permutation(num_feats)[:1024]
self.feature_masks[k] = mask
for k, v in res.items():
if 'kernel' in k:
agg_res[k] = v
elif k in self.Config.target_layers:
feats = np.reshape(v, [v.shape[0], -1])
feats = feats[:, self.feature_masks[k]]
agg_res[k].append(feats)
else:
agg_res[k].append(v)
return agg_res
def subselect_tfrecords(self, path):
"""
Illustrates how to subselect files for training or validation
"""
all_filenames = os.listdir(path)
rng = np.random.RandomState(seed=SEED)
rng.shuffle(all_filenames)
return [os.path.join(path, fn) for fn in all_filenames
if fn.endswith('.tfrecords')]
def parse_imagenet_meta_data(self, results):
"""
Parses the meta data from tfrecords into a tabarray
"""
meta_keys = ["labels"]
meta = {}
for k in meta_keys:
if k not in results:
raise KeyError('Attribute %s not loaded' % k)
meta[k] = np.concatenate(results[k], axis=0)
return tb.tabarray(columns=[list(meta[k]) for k in meta_keys], names = meta_keys)
def get_imagenet_features(self, results, num_subsampled_features=None):
features = {}
for layer in self.Config.target_layers:
feats = np.concatenate(results[layer], axis=0)
feats = np.reshape(feats, [feats.shape[0], -1])
if num_subsampled_features is not None:
features[layer] = \
feats[:, np.random.RandomState(0).permutation(
feats.shape[1])[:num_subsampled_features]]
return features
def imagenet_classification(self, results):
"""
Performs classification on ImageNet using a linear regression on
feature data from each layer
"""
retval = {}
meta = self.parse_imagenet_meta_data(results)
features = self.get_imagenet_features(results, num_subsampled_features=1024)
# Subsample to 100 labels
target_labels = np.unique(meta['labels'])[::10]
mask = np.isin(meta['labels'], target_labels)
for layer in features:
features[layer] = features[layer][mask]
meta = tb.tabarray(columns=[list(meta['labels'][mask])], names=['labels'])
#print "Features:", features['bn1'].shape
print "Labels:", np.unique(meta['labels']).shape
for layer in features:
layer_features = features[layer]
print('%s Imagenet classification test...' % layer)
category_eval_spec = {
'npc_train': None,
'npc_test': 5,
'num_splits': 3,
'npc_validate': 0,
'metric_screen': 'classifier',
'metric_labels': None,
'metric_kwargs': {'model_type': 'svm.LinearSVC',
'model_kwargs': {'C':5e-3}},
'labelfunc': 'labels',
'train_q': None,
'test_q': None,
'split_by': 'labels',
}
res = compute_metric_base(layer_features, meta, category_eval_spec)
res.pop('split_results')
retval['imagenet_%s' % layer] = res
return retval
if __name__ == '__main__':
"""
Illustrates how to run the configured model using tfutils
"""
base.get_params()
m = ImageNetClassificationExperiment()
params = m.setup_params()
base.test_from_params(**params)
"""
exp='exp_reg'
batch=50
crop=224
for iteration in [10000, 20000, 40000]:
print("Running imagenet model at step %s" % iteration)
base.get_params()
m = ImageNetClassificationExperiment('exp_reg', iteration, 32, 224)
params = m.setup_params()
base.test_from_params(**params)
"""
|
9ea53752081cd9e803b5bf01739a69b1da21b100 | Anubhav27/DataWeave_Programming_Test | /dataweave_DataStore.py | 1,707 | 4.03125 | 4 | """
This is Question 1 of the assignment
I have created a Key Value Data Store which can perform following operation:
Add(key,value)
Get(key)
delete(key)
Solution:
Here in the solution i tried to create a DataStore class and where the number of versions for a key is taken from "datastore_configuration" file
and based on number of configuration for values of key values are appended to a list and if new value to be added exceeds this version it will be discarded.
"""
class DataStore:
dataStore={}
l = []
def __init__(self,num_versions):
self.num_versions = num_versions
def add(self,key,value):
print "adding key value in a datastore"
local_list = []
if key in self.dataStore.keys():
print "key with %s is there so appending to it" % key
local_list = self.dataStore.get(key)
if (len(local_list) < int(self.num_versions)):
local_list.append(value)
self.dataStore[key] = local_list
print self.dataStore
else:
print "key %s is not there" % key
local_list.append(value)
self.dataStore[key] = local_list
print self.dataStore
def get(self,key):
print "return latest value of %s" % key
loc_list = self.dataStore[key]
print loc_list[len(loc_list)-1]
def delete(self,key):
del self.dataStore[key]
print "key %s is deleted" % key
version=""
with open('datastore_configuration') as f:
for line in f:
version = line
ds = DataStore(version)
ds.add(1,1)
ds.add(1,2)
ds.add(1,3)
ds.add(1,4)
ds.add(2,1)
ds.add(2,2)
ds.add(2,3)
ds.get(1)
ds.delete(1)
|
4aa7b57b017eff732c2b6e045ff29db48b0f4b5f | jmhuang1995/Tetris_Ai | /halgo.py | 2,184 | 3.515625 | 4 | def empty_(cell):
return cell == 0
def blocked_(cell):
return cell != 0
def blocks_amount(board):
i = 0
for row in board:
for cell in row:
if blocked_(cell):
i += 1
return i
def max_board_height(board):
for idx, row in enumerate(board):
for cell in row:
if blocked_(cell):
return len(board) - idx - 1
def block_avgerage_height(board):
block_total_height = 0
for height, row in enumerate(reversed(board[1:])):
for cell in row:
if blocked_(cell):
block_total_height += height
return block_total_height / blocks_amount(board)
def find_holes(board):
holes = []
blocks_in_colunm = False
for x in range(len(board[0])):
for y in range(len(board)):
if blocks_in_colunm and empty_(board[y][x]):
holes.append((x,y))
elif blocked_(board[y][x]):
blocks_in_colunm = True
blocks_in_colunm = False
return holes
def holes_amount(board):
return len(find_holes(board))
def blocks_above_hole_amount(board):
i = 0
for hole_x, hole_y in find_holes(board):
for y in range(hole_y-1, 0, -1):
if blocked_(board[y][hole_x]):
i += 1
else:
break
return i
def gaps_amount(board):
gaps = []
sequence = 0
board_copy = []
for y in range(len(board)):
board_copy.append([1] + board[y] + [1])
#find gaps
for y in range(len(board_copy)):
for x in range(len(board_copy[0])):
if sequence == 0 and blocked_(board_copy[y][x]):
sequence = 1
elif sequence == 1 and empty_(board_copy[y][x]):
sequence = 2
elif sequence == 2:
if blocked_(board_copy[y][x]):
gaps.append(board_copy[y][x - 1])
sequence = 1
else:
sequence = 0
return len(gaps)
|
740a5ab1bd4ac800c9857c436760ff6320eeca29 | viveshy/python-sandbox | /12-py_json.py | 385 | 3.71875 | 4 | # JSON is commonly used with data APIS. Here how we can parse JSON into a Python dictionary
import json
# Sample JSON
userJSON = '{"first_name": "vivesh", "last_name": "yadav", "age": 21}'
# Parse to dict
user = json.loads(userJSON)
print(user)
print(user['first_name'])
car = {'brand': 'Tesla', 'model': 'X', 'body-style':'5 door SUV'}
carJSON = json.dumps(car)
print(carJSON)
|
09dbe3b7a0b697c209e0cc22676dd79d1f7b94dc | SunilPadikarManjunatha/K-Similar-Strings | /ksimilar.py | 1,098 | 3.53125 | 4 | class Solution:
def kSimilarity(self, A: str, B: str) -> int:
a = list(A)
b = list(B)
k = 0
queue = []
queue.append(A)
result = {A:0}
i=0
while queue:
string = queue.pop()
items = self.get_poss_swaps(list(string),b)
if string == B: return result[string]
for item in items:
if item not in result:
result[item] = result[string] + 1
queue.append(item)
print(result)
def get_poss_swaps(self, arr, b):
for i, char in enumerate(arr):
if char != b[i]:
break
poss_list = []
for j in range(i+1, len(arr)):
if arr[j] == b[i]:
arr[j], arr[i] = arr[i], arr[j]
poss_list.append("".join(arr))
arr[i], arr[j] = arr[j], arr[j]
return poss_list
sol = Solution()
A = "abccaacceecdeea"
B = "bcaacceeccdeaae"
print(sol.kSimilarity(A,B))
A = "ab"
B = "ba"
print(sol.kSimilarity(A,B)) |
5f9f2f322497acb5f6986fa9c87f1a343edf5955 | Toan211/CS112_AlgorithmAnalyse | /IP.py | 941 | 3.546875 | 4 | def check(ip):
ip = ip.split(".")
for i in ip:
if(len(i) > 3 or int(i) > 255 or int(i) < 0):
return False
if(len(i) > 1 and int(i) == 0):
return False
if(len(i) > 1 and int(i) != 0 and i[0] == '0'):
return False
return True
def convert(ip):
size = len(ip)
if size > 12:
return []
snew = ip
l = []
for i in range(1, size - 2):
for j in range(i + 1, size - 1):
for k in range(j + 1, size):
snew = snew[:k] + "." + snew[k:]
snew = snew[:j] + "." + snew[j:]
snew = snew[:i] + "." + snew[i:]
# Check for the validity of combination
if check(snew):
l.append(snew)
snew = ip
return l
i = input()
s = convert(i)
for i in range (0,len(s)):
print(s[i]) |
99329e63248a8692b819b066bf92392efd3f831a | Toan211/CS112_AlgorithmAnalyse | /goldbachConjecture.py | 799 | 3.75 | 4 | def primess(n):
lis = [True] * n
for i in range(3,int(n**0.5)+1,2):
if lis[i]:
lis[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1)
return [2] + [i for i in range(3,n,2) if lis[i]]
def binarySearch (arr, l, r, x):
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
return True
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return False
num = int(input())
primes = primess(num)
count = 0
for i in range(len(primes)):
x = num - primes[i]
Result = binarySearch(primes,0,len(primes)-1,x)
if x < primes[i]:
break
if Result == True:
count = count + 1
print(count) |
4e7759522af8b94701fc4a9116fea845bb09f4c7 | elsandkls/SNHU_IT140_itty_bitties | /grocery_list.py | 13,180 | 3.984375 | 4 | # Grocery List Project
# example of a function:
def printCategory(category_list):
i = int(1)
stop = len(category_list) -1
# i. Identify: Item-based for loops
while i <= stop:
#iii. Identify: Accessing values in a list
print(i, str.capitalize(category_list[i]))
i= i+1;
print("\n")
return (0)
def printCustomerCart(customer_grocery_list):
# ii. Identify: Index-based (range) for loops
for i in range(0,len(customer_grocery_list),1):
print(i, customer_grocery_list[i])
# add pulling data from grocery_list_dictionary using the list to match the Uindex.
print("\n")
return (0)
def printGroceryList(grocery_list_dictionary, category_selection, category_list):
k = int(0)
k = len(grocery_list_dictionary)
if(category_selection != 0):
print("Category: \t ", str.capitalize(category_list[category_selection]))
print("Name: \t\t\t Price: \t Quantity: \t Size: \t ")
for i in range (0,k,1):
if(category_list[category_selection] == grocery_list_dictionary[i]['category'] ):
# iii. Identify: Accessing values using keys
print(grocery_list_dictionary[i]['Uindex'], str.capitalize(grocery_list_dictionary[i]['name']), "\t\t", grocery_list_dictionary[i]['cost'], "\t\t", grocery_list_dictionary[i]['quantity'], "\t\t\t", grocery_list_dictionary[i]['defmeasure'])
else:
print("UID:\t Cat:\t Name: \t\t\t Price: \t Q: \t Size: \t ")
for i in range (0,k,1):
# iii. Identify: Accessing values using keys
print(grocery_list_dictionary[i]['Uindex'], str.capitalize(grocery_list_dictionary[i]['category']), str.capitalize(grocery_list_dictionary[i]['name']), "\t\t", grocery_list_dictionary[i]['cost'], "\t\t", grocery_list_dictionary[i]['quantity'], "\t\t\t", grocery_list_dictionary[i]['defmeasure'])
print("\n")
return (0)
def printMenu(menu_content):
i = int(1)
stop = len(menu_content) -1
# i. Identify: Item-based for loops
while i <= stop:
#iii. Identify: Accessing values in a list
print(menu_content[i])
i= i+1;
print("\n")
return (0)
# Create dictionary with a grocery list.
# Assign the dictionary to the variable grocery_list
# i. Identify: Creating dictionaries
category_list = ['','dairy','meat','bakery','deli','canned','frozen','fruit','veggies','Misc']
# name, cost, quantity, available in the store -- groceries
# i. Identify: Creating dictionaries
grocery_list_dictionary = [{'Uindex':101, 'category':'dairy', 'name':'whole milk','cost':2,'quantity':1,'defmeasure':'1 gal' },
{'Uindex' : 102, 'category':'dairy', 'name':'creamer','cost':2,'quantity':1,'defmeasure':'64 fl oz' },
{'Uindex' : 103, 'category':'dairy', 'name':'heavy cream','cost':2,'quantity':1,'defmeasure':'1 qt' },
{'Uindex' : 107, 'category':'meat', 'name': 'eggs', 'cost': 5, 'quantity': 1,'defmeasure':'dozen'},
{'Uindex' : 108, 'category':'meat', 'name': 'sausage roll', 'cost': 5, 'quantity': 1,'defmeasure':'8 oz'},
{'Uindex' : 110, 'category':'meat', 'name': 'bacon thick', 'cost': 5, 'quantity': 1,'defmeasure':'16 oz'},
{'Uindex' : 116, 'category':'meat', 'name': 'chicken breast', 'cost': 5, 'quantity': 1,'defmeasure':'16 oz'},
{'Uindex' : 122, 'category':'bakery', 'name': 'dinner rolls', 'cost': 5, 'quantity': 1,'defmeasure':'bag'},
{'Uindex' : 123, 'category':'bakery', 'name': 'cupcakes', 'cost': 5, 'quantity': 1,'defmeasure':'tray (dozen)'},
{'Uindex' : 128, 'category':'deli', 'name': 'sliced turkey', 'cost': 5, 'quantity': 1,'defmeasure':'16 oz'},
{'Uindex' : 133, 'category':'deli', 'name': 'sliced salami', 'cost': 5, 'quantity': 1,'defmeasure':'16 oz'},
{'Uindex' : 134, 'category':'canned', 'name': 'pickles', 'cost': 5, 'quantity': 1,'defmeasure':'16 oz'},
{'Uindex' : 147, 'category':'canned', 'name': 'yams', 'cost': 5, 'quantity': 1,'defmeasure':'16 oz'},
{'Uindex' : 140, 'category':'frozen', 'name': 'ice cream cake', 'cost': 5, 'quantity': 1,'defmeasure':'gal'},
{'Uindex' : 151, 'category':'frozen', 'name': 'custard pie', 'cost': 5, 'quantity': 1,'defmeasure':'1'},
{'Uindex' : 156, 'category':'fruit', 'name': 'oranges', 'cost': 5, 'quantity': 1,'defmeasure':'bag'},
{'Uindex' : 169, 'category':'fruit', 'name': 'apples', 'cost': 5, 'quantity': 1,'defmeasure':'bag'},
{'Uindex' : 175, 'category':'veggies', 'name': 'pumpkin', 'cost': 5, 'quantity': 1,'defmeasure':'1 lb'},
{'Uindex' : 176, 'category':'veggies', 'name': 'green beans', 'cost': 5, 'quantity': 1,'defmeasure':'bag'},
{'Uindex' : 177, 'category':'veggies', 'name': 'corn cob', 'cost': 5, 'quantity': 1,'defmeasure':'bag'}]
# note to self, watch out for the lists, they are poitners, they are not unique in memory.
# Create dictionary with a customer grocery list.
# Assign the dictionary to the variable customer_grocery_list
# name, cost, quantity -- customers shopping cart - groceries
# i. Identify: Creating lists
customer_grocery_list=[]
question_count = int(3)
# menu for a simple grocery list and checkout..
# i. Identify: Creating lists
menu_main = [ " ",
"####################################",
"### Grocery List Script ###",
"####################################",
" 1. List and Select available categories. ",
" 2. List groceries. ",
" 3. Add groceries to shopping cart. ",
" 4. Remove groceries from shopping cart. ",
" 5. Check out.",
" 7. Exit program. ",
"####################################",
"####################################",
" ** Admin Access ** 0 ",
"####################################",
"####################################",
" "]
menu_admin= [ " ",
"####################################",
"### Admin Options ###",
"####################################",
" 1. Update item price. ",
" 2. Delete item from list. ",
" 3. Add item to list. ",
"####################################",
" "]
# create simple int variable
menu_start = int(0)
menu_stop = len(menu_main)
menu_myinc = int(1)
menu_selection = int(0)
admin_menu_selection = int(0)
category_selection = int(0)
category_name = str()
new_price = float()
#menu system
# 1. User Input
#iii. Identify: While loops
while menu_selection <= 6:
#print menu options
printMenu(menu_main)
menu_selection = input('Enter your seletion (1,2,3,4,5,6): ')
menu_selection = int(menu_selection)
if (menu_selection == 0):
#print menu options
printMenu(menu_admin)
admin_menu_selection = input('Enter your seletion (1,2,3): ')
admin_menu_selection = int(admin_menu_selection)
print('%i selected \n' % admin_menu_selection)
if (admin_menu_selection == 1):
# Change items price
printGroceryList(grocery_list_dictionary,0, category_list)
# ask for produt identifier
grocery_selection = input('Which item do you want to update? : ')
print("Updating item: ",grocery_selection)
# ask for new price
new_price = input('What is the new price? : ')
print("Price changing to: ",new_price)
# update the list with the new price.
# iv. Identify: Modifying values in a list
for i in range(0,len(grocery_list_dictionary),1):
grocery_selection = int(grocery_selection)
if (grocery_list_dictionary[i]['Uindex'] == grocery_selection):
grocery_list_dictionary[i]['cost'] = new_price
print("\n\n")
elif (admin_menu_selection == 2):
# Delete item from list.for i in range(menu_start,len(category_list),menu_myinc):
printGroceryList(grocery_list_dictionary,0, category_list)
# ask for produt identifier
grocery_selection = input('Which item do you want to delete? : ')
print("Delete item: ",grocery_selection)
grocery_selection = int(grocery_selection)
# ask for new price
status_check = input('Confirm you want to delete this item? (Y/N) : ')
print("Confirmed: ",status_check)
# update the list with the new price.
# iv. Identify: Modifying values in a list
for i in range(0,len(grocery_list_dictionary),1):
if (grocery_list_dictionary[i]['Uindex'] == grocery_selection):
del grocery_list_dictionary[i]
# ii. Identify: Removing key:value pairs
for i in range(0,len(category_list),1):
# print grocery list
printGroceryList(grocery_list_dictionary,i, category_list)
print("\n\n")
elif (admin_menu_selection == 3):
# Add item to list
# ii. Identify: Adding and removing key:value pairs
printGroceryList(grocery_list_dictionary,0, category_list)
# ask for new price
status_check = input('Do you want to add a new item? (Y/N) : ')
print("Confirmed: ",status_check)
# update the list with the new price.
# iv. Identify: Modifying values in a list
running_high_number = int(0)
for i in range(0,len(grocery_list_dictionary),1):
if (grocery_list_dictionary[i]['Uindex'] > running_high_number):
running_high_number = grocery_list_dictionary[i]['Uindex']
# ii. Identify: Adding key:value pairs
my_temp_dict = { }
my_temp_dict['Uindex'] = running_high_number +1
my_temp_dict['name'] = input('Product name? : ')
my_temp_dict['cost'] = input('Product Cost? : ')
my_temp_dict['quantity'] = input('Product Quanity? : ')
my_temp_dict['defmeasure'] = input('Product Size? : ')
my_temp_dict['category'] = "Misc"
print(my_temp_dict)
grocery_list_dictionary.append(my_temp_dict)
print("\n")
printGroceryList(grocery_list_dictionary,0, category_list)
print("\n\n")
elif (menu_selection == 1):
# 2. Loop through the category list
printCategory(category_list)
category_selection = input('Select a catagory: ')
print(category_selection)
category_selection = int(category_selection)
elif (menu_selection == 2):
# 2. Loop through the grocery list
printGroceryList(grocery_list_dictionary,category_selection, category_list)
elif (menu_selection == 3):
sub_menu_selection = str("Y")
while sub_menu_selection == "Y":
# 2. Loop through the grocery list
printGroceryList(grocery_list_dictionary,category_selection, category_list)
question_count = int(0)
while question_count <= 3:
question_count = question_count + 1
grocery_selection = input('Add to cart: ')
print("Adding item: ",grocery_selection)
#ii. Identify: Adding data from a list
customer_grocery_list.append(grocery_selection)
sub_menu_selection = input('Continue adding items? (Y/N) ')
elif (menu_selection == 4):
# remove groceries from cart.
# print cart
printCustomerCart(customer_grocery_list)
# ask customer which to remove
grocery_selection = input('Remove from cart: ')
print(grocery_selection)
# remove selection.
#ii. Identify: Removing data from a list
customer_grocery_list.remove(grocery_selection)
# ask customer if they would like to remove another
elif (menu_selection == 5):
# 3. Provide output to the console
customer_sub_total = int(0)
product_index = int(0)
# print shopping cart contents
printCustomerCart(customer_grocery_list)
# iii. Identify: Accessing values in a list
# iv. Identify: Modifying values in a list
for x in range(0,len(customer_grocery_list),1):
product_index = int(customer_grocery_list[x])
for i in range(0,len(grocery_list_dictionary),1):
if (grocery_list_dictionary[i]['Uindex'] == product_index):
customer_sub_total = customer_sub_total + grocery_list_dictionary[i]['cost']
# access product totals and calculate the sub total
# output total to customer
customer_sub_total = float(customer_sub_total)
print("Cart total: ", '${:,.2f}'.format(customer_sub_total ))
# write the sub total to customer list for later use
# Do we need to alculate tax on food items for this program?
# Ohio has no food tax (my state).
else:
print("End of program.")
|
23e0c28459fd418f5e56ba9ae742bd5b0329447d | elsandkls/SNHU_IT140_itty_bitties | /x10.py | 675 | 4.03125 | 4 | # Get our input from the command line
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
# convert strings to integers
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
# Your code goes here
# numbers now contains the list of integers
# You should multiply every Nth element by M.
# (do not multiply the 0th element)
#
MyIncrement = int(1)
CheckIt = int(N)
# Write your code below
for i in range(0,len(numbers),1):
print(MyIncrement)
if(MyIncrement == CheckIt):
numbers[i] = numbers[i] * M
CheckIt = CheckIt + N
print("updated it")
MyIncrement = MyIncrement +1
print(numbers)
|
c3a30ed49821b8d9bbce40e9cc70d9b54e3100dc | elsandkls/SNHU_IT140_itty_bitties | /email_regex_example.py | 305 | 3.5 | 4 | # email validation
emailList = ['cersei.lannister@got.eu', 'j.a.m.i.eLan@goteu', 'nedstark_got.eu']
emailValidation = re.compile(r'''([a-zA-Z0-9._&=-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z] (2,4)))''', re.VERBOSE)
for email in emailList:
if re.match(emailValidation, email):
print(email, "is valid")
else:
print(email, "is invalid") |
92e296b5132802978932b62ddab03030d636785d | elsandkls/SNHU_IT140_itty_bitties | /example_1_list.py | 1,593 | 4.34375 | 4 |
# Get our lists from the command line
# It's okay if you don't understand this right now
import sys
list1 = sys.argv[1].split(',')
list2 = sys.argv[2].split(',')
#
# Print the lists.
#
# Python puts '[]' around the list and seperates the items
# by commas.
print(list1)
print(list2)
#
# Note that this list has three different types of items
# in the container: an Integer, a String, and a Boolean.
#
list3 = [1,"red", True]
print(list3)
strList = ['Alice', 'Shahneila', 'Bobx, 'Tariq']
numList = [1, 3.141, 5, 17.1, 100]
numList = []
numList.append(4)
# create a list
aList = [ 'Alice', 'Shahneila', 'Bob', 'Tariq' ]
print(aList)
# change the second element
aList[1] = 'Sean'
print(aList)
# create an empty list
numList = []
# append some items to the empty list
numList.append(1)
numList.append(2)
numList.append(4)
print(numList)
# insert an element at a specific index
numList.insert(2, 3)
print(numList)
aString = '12345'
# use the len() function to get the length of a string
print('the string has a length of:')
print(len(aString))
aList = [1,2,3,4,5]
# you can also use the len() function to get the length of a list
print('the list has a length of:')
print(len(aList))
myList = [1,3,5,7,9]
stop = len(myList)
print('the list has ' + str(stop) + ' elements')
aRange = range(0, stop)
for i in aRange:
print(myList[i])
# short version
print('a shorter way of creating ranges for looping')
for i in range(0, len(myList)):
print(myList[i])
# display every second item
print('range step of 2')
for i in range(0, len(myList), 2):
print(myList[i])
|
b16d624f650ddfffc987202f1a51c15a0e98224b | elsandkls/SNHU_IT140_itty_bitties | /experiment.py | 406 | 3.90625 | 4 | # Write experimental code below
print ("Your experiemental code")
# Get N from the command line
import sys
N = int(sys.argv[1])
# Your code goes here
# We will pass in a value, N.
# You should write a program that outputs all values from 0 up to an including N.
start = int(0)
stop = int(N + 1)
print 'Start: ', start, '\n'
print 'Stop: ', stop , '\n'
for i in range(start, stop, +1):
print(i)
|
2bc8716889789123086992553fd8501964bb993d | andressequeda/ejercicio3 | /ejercicio3.py | 450 | 4.0625 | 4 | numero1 = int ( input ( "Ingrese el primer número:" ))
numero2 = int ( input ( "Ingrese el segundo número:" ))
print ( "La suma de los números es:" , numero1 + numero2 )
print ( "La resta de los números es:" , numero1 - numero2 )
print ( "La multiplicacion de los números es:" , numero2 * numero2 )
print ( "La division de los números es:" , numero1 / numero2 )
print ( "El residuo de los números es:" , numero1 % numero2 ) |
cf679751430149abfea0f8f11c6bb2cffaa218bf | aazhbd/numerical | /primesdb/saveprimesinsqlite.py | 1,914 | 3.96875 | 4 | import random
import sys
import sqlite3
def is_probable_prime(n, k = 7):
"""use Rabin-Miller algorithm to return True (n is probably prime) or False (n is definitely composite)"""
#print "Starting to check whether " + str(n) + " is prime"
if n < 6: # assuming n >= 0 in all cases... shortcut small cases here
return [False, False, True, True, False, True][n]
elif n & 1 == 0: # should be faster than n % 2
return False
else:
s, d = 0, n - 1
while d & 1 == 0:
s, d = s + 1, d >> 1
# Use random.randint(2, n-2) for very large numbers
for a in random.sample(xrange(2, min(n - 2, sys.maxint)), min(n - 4, k)):
x = pow(a, d, n)
if x != 1 and x + 1 != n:
for r in xrange(1, s):
x = pow(x, 2, n)
if x == 1:
return False # composite for sure
elif x == n - 1:
a = 0 # so we know loop didn't continue to end
break # could be strong liar, try another a
if a:
return False # composite if we reached end of this loop
return True # probably prime if reached end of outer loop
def main():
db = sqlite3.connect('primes99')
cursor = db.cursor()
cursor.execute('''create table if not exists primes(id INTEGER PRIMARY KEY, prime INTEGER)''')
db.commit()
num = 0
cursor.execute('INSERT INTO primes(prime) VALUES(' + str(2) + ')')
db.commit()
num = num + 1
i = 3
while True:
if is_probable_prime(i, 2):
cursor.execute('INSERT INTO primes(prime) VALUES('+ str(i) +')')
db.commit()
print str(i) + ' is prime and inserted'
num = num + 1
i += 2
if i >= 9999999999:
print "total collected : ", num
break
db.close()
if __name__ == '__main__':
main()
|
c9f45554809231162d7dc7cf5b921ed427ffa944 | sacherjj/dailyprogrammer | /20170710_challenge_323_easy_3sum/three_sum_python/three_sum.py | 1,873 | 3.765625 | 4 | import time
from random import choice
from itertools import combinations
def zero_optimal(num_list):
"""
Quadratic algorithm from
https://en.wikipedia.org/wiki/3SUM
"""
output = set()
num_list.sort()
length = len(num_list)
for i in range(length-2):
a = num_list[i]
start = i + 1
end = length - 1
while start < end:
b = num_list[start]
c = num_list[end]
if a + b + c == 0:
output.add((a, b, c))
end -= 1
elif a + b + c > 0:
end -= 1
else:
start += 1
return output
def zero_sum(num_list):
"""
My initial solution
"""
num_list.sort()
solution = set()
for i, val_i in enumerate(num_list[:-2]):
for j in range(i+1, len(num_list) - 1):
val_j = num_list[j]
for k in range(j+1, len(num_list)):
val_k = num_list[k]
if val_i + val_j + val_k == 0:
solution.add((val_i, val_j, val_k))
return solution
def zero_comb(num_list):
"""
Another solution in Thread
"""
return {tuple(sorted(n)) for n in combinations(num_list, 3) if sum(n) == 0}
inputs = []
with open('../test_data.txt', 'r') as f:
for line in f.readlines():
inputs.append(line.rstrip('\n'))
methods = [('itertools', zero_comb), ('looping', zero_sum), ('quadratic', zero_optimal)]
methods = [('quadratic', zero_optimal)]
for vals in inputs:
print('Evaluating {}'.format(vals))
for method in methods:
method_name, method_obj = method
num_list = [int(x) for x in vals.split(' ')]
start = time.time()
solution = method_obj(num_list)
print('Time: {} for {}'.format(time.time()-start, method_name))
print(solution)
print('---')
|
215518cfa49b03d077917126f678839990deccc1 | MasudHaider/Think-Python-2e | /chap8.py | 1,558 | 3.9375 | 4 | # fruit = 'banana'
# index = 0
# while index < len(fruit):
# letter = fruit[index]
# print(letter)
# index += 1
# def backward_letter(str):
# length = len(str)-1
# while length >= 0:
# print(str[length])
# length -= 1
#
#
# def ducklings():
# prefix = 'JKLMNOPQ'
# suffix = 'ack'
#
# for letter in prefix:
# if letter == 'O' or letter == 'Q':
# print(letter + 'u' + suffix)
# else:
# print(letter + suffix)
# def find(word, letter, index):
# while index < len(word):
# if word[index] == letter:
# return index
# index += 1
# return -1
# def no_e(string, char, index):
# counter = 0
# while index < len(string):
# if string[index] == char:
# counter = counter + 1
# index = index+1
# print(counter)
# def in_both(w1, w2):
# for l in w1:
# if l in w2:
# print(l)
# word = 'orange'
#
# if word < 'banana':
# print(word + ' before banana')
# elif word > 'banana':
# print(word + ' after banana')
# else:
# print('All right, banana')
def is_reverse(w1, w2):
if len(w1) != len(w2):
return False
i = 0
j = len(w2)-1
while not j < 0:
print(i, j)
if w1[i] != w2[j]:
return False
i = i+1
j = j-1
return True
# backward_letter('deepwork')
# ducklings()
# print(find('duckduckgo', 'o', 3))
# no_e('CSrankings', 'Q', 1)
# in_both('apple', 'orange')
print(is_reverse('pots', 'stop'))
|
ceb29241ace6c0a9b6c6b35bea9ec8d931e59402 | MasudHaider/Think-Python-2e | /Exer-6-2.py | 248 | 3.6875 | 4 | def ack(m, n):
if m < 0 or n < 0:
print("Ackermann is not defined for negative integers")
elif m == 0:
return n+1
elif n == 0:
return ack(m-1, 1)
else:
return ack(m-1, ack(m, n-1))
print(ack(3, 4))
|
7add89c47bb6e5b3a49504244acc952a91040d31 | MasudHaider/Think-Python-2e | /Exer-5-3(1).py | 555 | 4.21875 | 4 | def is_triangle(length1, length2, length3):
case1 = length1 + length2
case2 = length1 + length3
case3 = length2 + length3
if length1 > case3 or length2 > case2 or length3 > case1:
print("No")
elif length1 == case3 or length2 == case2 or length3 == case1:
print("Degenerate triangle")
else:
print("Yes")
prompt = "Enter value for length1: "
a = int(input(prompt))
prompt = "Enter value for length2: "
b = int(input(prompt))
prompt = "Enter value for length3: "
c = int(input(prompt))
is_triangle(a, b, c)
|
cf94aefd27b4487ee51ca035bc8e7a848d905163 | MasudHaider/Think-Python-2e | /Exer-9-3.py | 671 | 3.65625 | 4 | def avoids(words, forbw):
for letter in forbw:
if letter in words:
return False
return True
def permutations_with_repetition(permutable):
base = len(permutable)
for n in range(base ** base):
yield "".join(permutable[n // base ** (base - d - 1) % base] for d in range(base))
if __name__ == '__main__':
for p in permutations_with_repetition("lion"):
print(p)
has_no_fl = True
forbidden_letter = input("Enter forbidden word: ")
fin = open('words.txt')
for line in fin:
word = line.strip()
has_no_fl = avoids(word, forbidden_letter)
if has_no_fl:
print(word)
|
5a32c8dce11d4809a1abf94a0373c4fff7bebef3 | MasudHaider/Think-Python-2e | /chp6.py | 1,408 | 4 | 4 | import math
def area(radius):
a = math.pi * radius**2
return a
def absolute_value(x):
if x < 0:
return -x
else:
return x
def compare(x, y):
if x > y:
return 1
elif x == y:
return 0
else:
return -1
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
def hypotenuse_length(leg1, leg2):
print(leg1, leg2)
squared = leg1**2 + leg2**2
leg3 = math.sqrt(squared)
return leg3
def circle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
def is_divisible(x, y):
return x % y == 0
def is_between(x, y, z):
return z >= x <= y
def factorial(n):
space = " " * (4 * n)
print(space, 'factorial', n)
if not isinstance(n, int):
print("Factorial is only defined for integers")
return None
elif n < 0:
print("Factorial is not defined for negative integers")
return None
elif n == 0:
print(space, 'returning 1')
return 1
else:
recurse = factorial(n-1)
result = n * recurse
print(space, 'returning', result)
return result
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
# print(fibonacci(3))
print(factorial(4))
|
f364bf7ee163bf21f658ab8653dd53da0ea34fb2 | MasudHaider/Think-Python-2e | /Exer-7-2.py | 263 | 3.765625 | 4 | import math
def eval_loop():
while True:
ein = input()
if not ein == 'done':
eval_result = eval(ein)
print(eval_result)
else:
return eval_result
if __name__ == '__main__':
print(eval_loop())
|
1749c9210031638cf34bcf1b8524166a5cd21d6d | MasudHaider/Think-Python-2e | /Exer-10-2.py | 213 | 3.71875 | 4 | def cumsum(seq):
new_list = []
for i in range(0, len(seq)):
new_list.append(sum(seq[0:i+1]))
return new_list
if __name__ == '__main__':
my_list = [1, 2, 3, 67]
print(cumsum(my_list))
|
b6baad438e3ddeaa39089ce83a2cd2cdf233b6ce | AdityaVashista30/Pet-Classifier-Using-CNN | /Pet Classifier.py | 3,351 | 3.546875 | 4 |
import tensorflow
from keras_preprocessing.image import ImageDataGenerator
#PART 1: IMAGE PREPROCESSING
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
"""### Generating images for the Test set"""
test_datagen = ImageDataGenerator(rescale = 1./255)
"""### Creating the Training set"""
training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size = (128, 128),
batch_size = 32,
class_mode = 'binary')
"""### Creating the Test set"""
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size = (128, 128),
batch_size = 32,
class_mode = 'binary')
#PART 2: Creating CNN Classifiaction Model
cnn=tensorflow.keras.models.Sequential()
#ADDING FIRST LAYER
#STEP 1: convolution
cnn.add(tensorflow.keras.layers.Conv2D(filters=64,kernel_size=3,input_shape=[128, 128, 3],padding="same", activation="relu"))
#STEP 1: convolution
cnn.add(tensorflow.keras.layers.MaxPool2D(pool_size=2, strides=2, padding='valid'))
#ADDING 2nd LAYER
cnn.add(tensorflow.keras.layers.Conv2D(filters=64, kernel_size=3, padding="same", activation="relu"))
cnn.add(tensorflow.keras.layers.MaxPool2D(pool_size=2, strides=2, padding='valid'))
#STEP 3: FLATTENING (LAYER FINAL)
cnn.add(tensorflow.keras.layers.Flatten())
#STEP 4: FULL CONNECTION
cnn.add(tensorflow.keras.layers.Dense(units=128, activation='relu'))
"""### Step 5 - Output Layer"""
cnn.add(tensorflow.keras.layers.Dense(units=1, activation='sigmoid'))
### Compiling the CNN
cnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
#FITTING AND TESTING
cnn.fit(training_set,
steps_per_epoch = (8048/32),
epochs = 32,
validation_data = test_set,
validation_steps = (2000/32))
#PREDICTING
import numpy as np
from keras_preprocessing import image
testImage1=image.load_img('dataset/single_prediction/cat_or_dog_1.jpg',target_size=(128,128))
testImage2=image.load_img('dataset/single_prediction/cat_or_dog_2.jpg',target_size=(128,128))
testImage1=image.img_to_array(testImage1)
testImage2=image.img_to_array(testImage2)
testImage1=np.expand_dims(testImage1,0)
testImage2=np.expand_dims(testImage2,0)
results=[cnn.predict(testImage1),cnn.predict(testImage2)]
for i in range(len(results)):
if results[i][0,0]==1:
print("image ",i+1," is dog")
else:
print("image ",i+1," is cat")
#SAVING MODEL
cnn.save("pet_classifier.h5")
#DELETING MODEL
del cnn
#OPENING SAVED MODEL
from tensorflow.keras.models import load_model
classifier=load_model("pet_classifier.h5")
test3=image.load_img('dataset/single_prediction/unkown.jpg',target_size=(128,128))
test3=image.img_to_array(test3)
test3=np.expand_dims(test3,0)
if(classifier.predict(test3)[0][0]==1):
print("it is dog")
else:
print("it is cat")
|
afc0ab954176bdcbbb49b4415431c49278c9628c | kchow95/MIS-304 | /CreditCardValidaiton.py | 2,340 | 4.15625 | 4 | # Charlene Shu, Omar Olivarez, Kenneth Chow
#Program to check card validation
#Define main function
def main():
input_user = input("Please input a valid credit card number: ")
#Checks if the card is valid and prints accordingly
if isValid(input_user):
print(getTypeCard(input_user[0]))
print("The number is valid")
else:
print("Your credit card number is invalid")
#define isvalid returns true if the card is valid
def isValid(card_number):
valid_card = True
#Checks the numbers first
check_numbers = (sumOfDoubleEvenPlace(card_number) + sumOfOddPlace(card_number))%10
prefix = getPrefix(card_number)
#checks the parameters for the card
#not long enough or too long
if 13 >= getSize(card_number) >=16:
valid_card = False
#the numbers don't add up
elif(check_numbers != 0):
valid_card = False
#prefix isn't valid
elif prefixMatched(card_number, prefix) == False:
print(prefix)
valid_card = False
return valid_card
#sums the even places with double the int
def sumOfDoubleEvenPlace(card_number):
step = len(card_number)-2
total = 0
while step >= 0:
total+= (getDigit(2*int(card_number[step])))
step-=2
return total
#Gets the digit for the double even place function, takes out the 10s place and subtracts by one
def getDigit(digit):
return_digit = digit
if(digit >= 10):
return_digit = (digit - 10) + 1
return return_digit
#Gets the digit for the odd places from the end of the card_number and sums them
def sumOfOddPlace(card_number):
step = len(card_number)-1
total = 0
while step >= 0:
total += int(card_number[step])
step -= 2
return total
#Checks the number d if it falls into one of the four categories
def prefixMatched(card_number, d):
if(int(d) != 4 and int(d) != 5 and int(d) != 6 and int(d) != 37):
return False
else:
return True
#returns the size of the card number
def getSize(card_number):
return len(card_number)
#Returns the type of card it is
def getTypeCard(num):
num = int(num)
if(num == 4):
return "Your card type is Visa"
elif(num == 5):
return "Your card type is MasterCard"
elif(num == 6):
return "Your card type is Discover"
else:
return "Your card type is American Express"
#gets the second number if the card starts with a 3
def getPrefix(card_number):
if card_number[0] == "3":
return card_number[:2]
else:
return card_number[0]
main()
|
ddba8ae517ee2e4620f25b8fdc227fc3369c60d9 | cadracks-project/quaternions | /examples/quaternion_example.py | 222 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
r"""quaternion use example"""
from quaternions.quaternion import Quaternion
q = Quaternion()
print(q)
print(q.normalize())
print(q.conjugate())
q = Quaternion(a=2, b=3)
print(q)
|
d057be1139247fd438e9d8bfb7fff8721ec8efb3 | mxizhang/ScrapyCounty | /ScrapyCountyFlip/hunterdon_save.py | 3,133 | 3.5625 | 4 | import urllib2
import requests
from openpyxl import load_workbook
import csv
FILENAME_PDF = "sale.pdf"
FILENAME_CSV = "sale.xlsx"
def hunterdon_save():
download_file("http://www.co.hunterdon.nj.us/sheriff/SALES/sales.pdf")
convert_to_xlsx()
csv_read()
def download_file(download_url):
response = urllib2.urlopen(download_url)
file = open(FILENAME_PDF, 'wb')
file.write(response.read())
def convert_to_xlsx():
try:
files = {'f': (FILENAME_PDF, open(FILENAME_PDF, 'rb'))}
response = requests.post("https://pdftables.com/api?key=lhfxwj5qn8jg&format=xlsx-single", files=files) # $50 for 2500 pdfs
response.raise_for_status() # ensure we notice bad responses
with open(FILENAME_CSV, "wb") as f:
f.write(response.content)
f.close()
except IOError as e:
print "Error: File does not appear to exist."
def csv_read():
wb = load_workbook(filename='sale.xlsx', read_only=True)
ws = wb['PDFTables.com'] # ws is now an IterableWorksheet
list_all = []
list_all.append(['sale_date', 'sheriff_no', 'upset', 'att_ph', 'case_no', 'plf', 'att', 'address', 'dfd', 'schd_data'])
item = [0 for x in range(10)]
l = list(ws.rows)
num = 0
for index, row in enumerate(l):
if row[0].value == 'Case #':
#print 'Case: ' + str(l[index+1][0].value) + '/Date: ' + l[index+1][1].value + '/Asset: ' + str(l[index+1][4].value) + '/Address: ' + l[index+1][5].value
item = [0 for x in range(10)]
item[0] = l[index+1][1].value #Date
item[1] = str(l[index+1][0].value) #Caseno
if l[index][5].value == 'JUDGEMENT':
item[2] = l[index+1][5].value #asset
num = 5
elif l[index][4].value == 'JUDGEMENT':
item[2] = l[index+1][4].value #asset
num = 4
else:
item[2] = l[index+1][3].value
num = 3
#print l[index+1][num+1].value
try:
item[7] = str(l[index+1][num+1].value) + l[index+1][num+2].value #address
except:
item[7] = str(l[index+1][num+1].value) #address
#print 'case#: '+ item[1] + '/asset: ' + l[index+1][num].value
elif row[num+1].value == 'City':
city = l[index+1][num+1].value.split(' ')
for index in range(len(city)):
if city[index] == 'OF':
#print item[7]
#print " ".join(city[index+1:])
item[7] = item[7] + " " + " ".join(city[index+1:])
elif row[0].value == 'Plaintiff':
item[5] = l[index+1][0].value
elif row[0].value == 'Defendant':
item[8] = l[index+1][0].value
elif row[num+1].value == 'FIRM':
item[6] = l[index+1][num+1].value
elif row[num+1].value == 'TELEPHONE':
item[3] = l[index+1][num+1].value
print item
list_all.append(item)
with open("hunterdon_items.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(list_all)
|
dd7b7315ee7d3cfd75af1a924c0fa5f2d0ab731d | syeutyu/Day_Python | /01_Type/String.py | 1,380 | 4.125 | 4 | # 문자열 문자, 단어 등으로 구성된 문자들의 집합을 나타냅니다.
# 파이썬에는 4개의 문자열 표현 방법이 존재합니다.
a = "Hello Wolrd" #1
a = 'Hello Python' #2
a = """Python Hello""" #3
a = '''Python String''' #4
# 1. 문자열에 작은 따옴표를 포함시킬경우를 위해 제작
# Python's very good 을문자열로 하기위해서는? a = "Python's very good"
# 2. 위와 같이 문자열에 큰 따옴표를 표함하기위해서 제작되었다
# I want Study "Python" => a = 'I want Study "Python"'
# 3. 파이썬에서 줄바꿈을 위해서는 \n을 삽입하여 처리한다
# 이러한 불편함을 줄이기위해 3,4번을 사용하는데
# multiLine = '''
# Is very
# Simple! '''
# 문자열 처리방법
one = 'this'
two = 'is first'
print(one + two) # this is first
# 일반적인 + 수식을 이용하여 처리하는 문자열 더하기
one = "test"
print(one * 2) # testtest
# 문자열을 곱하면 파이썬은 곱한수만큼의 문자열을 반복한다
one = "I want Study Python..."
print(one[3]) # a
# 문자열 슬라이싱을 배열이 아니더라도 문자를 얻을 수 있다.
print(one[0:5]) # I want
# 문자열 슬라이싱을 [시작번호 : 끝 번호]와 [: 끝번호]로 문자를 얻을 수 있다.
# 관련 함수
# count 문자 개수 세기
# count('문자') 문자가 나온 수 출력 |
ef63dbd450a1f14f64ba393d9f02637f31ef742e | MGarrod1/rgg_ensemble_analysis | /rgg_ensemble_analysis/sql_utils.py | 9,520 | 3.6875 | 4 | """
Functions to be used for reading
and writing data to SQL databases
"""
import sqlite3
import sys
import pdb
import pickle
"""If importing MySQLdb doesn't work then we
must isntead import the connector"""
try :
import MySQLdb
except :
print("Importing mysql as MySQLdb")
import mysql.connector as MySQLdb
def connect_to_maths_cluster_db() :
#Details for accessing the database on the maths cluster:
file_name = "maths_clust_database_details"
#Load details in from a pickled dictionary
with open(file_name + '.pickle', 'rb') as handle:
details = pickle.load(handle)
host = details["host"]
user = details["user"]
passwd = details["passwd"]
db = details["db"]
connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cursor = connection.cursor()
return connection , cursor
def find_sql_type_string(variable) :
"""
Given a python variable return the
sql type string appropriate for saving it
Current variable lengths used for SQL e.g VARCHAR(10)
are arbitary for now.
e.g if we want to save an int nto the SQL database
Parameters
----------------
variable : some variable in python
Returns
----------------
string specifying the variable type
to save this as in an SQL database.
"""
if type(variable).__name__ == 'str' :
return "VARCHAR(30)"
elif type(variable).__name__ == 'float64' or type(variable).__name__== 'float' :
#return "FLOAT(5,4)"
return "DOUBLE"
elif type(variable).__name__ == 'int' or type(variable).__name__ == 'int64' :
return "INT(20)"
else:
#Exit if we detect a variable which is not one of supported types.
print("Error: Found a {}\nCurrently only supports int, str, float data types".format(type(variable)) )
sys.exit(1)
def convert_to_supported_type(variable) :
"""
Converts variables into types which are
supported by MySQL.
Types such as float64 are not supported
by SQL.
Inspired by:
https://stackoverflow.com/questions/17053435/mysql-connector-python-insert-python-variable-to-mysql-table
"""
if type(variable).__name__ == 'float64' :
return float(variable)
elif type(variable).__name__ == 'int64' :
return int(variable)
else :
return variable
def Make_SQL_Table(database_name,variable_dict,table_name,connect_to_server=True):
"""
Make an SQL database containing the graph
properties which we are interested in.
Parameters
-----------------
database_name : str
String specifying the name and location of the SQL database.
variable_names : dict
Dictionary containing variable types as keys.
table_name : str
Name of the table to create within the database.
connect_to_server : Bool (optional)
True is the database is hoted on some server.
"""
if connect_to_server==True :
connection, cursor = connect_to_maths_cluster_db()
else :
#Open the connection to the databse:
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
#Alernative command if we don't have an integar primary key:
sql_command = """CREATE TABLE IF NOT EXISTS {} (""".format(table_name)
#Loop through the variables and their types in order to build the table.
for k in variable_dict.keys() :
sql_command += k + " " + find_sql_type_string(variable_dict[k]) + ","
#remove final comma:
sql_command = sql_command[:-1]
sql_command = sql_command + ");"
cursor.execute(sql_command)
connection.commit()
connection.close()
def find_column_names(database_name,table_name,connect_to_server=True) :
"""
Return the names of the columns of a specific table
in the database of interest.
Parameters
--------------
database_name : str
file path to the databse of interest
tabel_name : str
name of the table within the database.
Returns
-------------
column_names : list of str
Containing the names of the different graph properties
stored in the SQL database.
"""
if connect_to_server==True :
connection, cursor = connect_to_maths_cluster_db()
else :
#Open the connection to the databse:
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
#Extecute a command so that the cursor is active:
stuff = cursor.execute('select * from {}'.format(table_name) )
#Pull out column names:
column_names = [ i[0] for i in cursor.description ]
connection.close()
return column_names
def Save_Dict_to_SQL(database_name,variable_dict,table_name,connect_to_server=True) :
"""
Save a row of values to an SQL database.
Parameters
-----------------
database_name : str
file path to the database
variable_dict : dict
Dictionary containing keys corresponding to the relevant column headers
and values correesponding to those to be saved in the table.
table_name : str
Name of table in the database to save the dictionary to.
"""
#Open the database:
if connect_to_server==True :
connection, cursor = connect_to_maths_cluster_db()
else :
#Open the connection to the databse:
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
params = list( variable_dict.values() )
#Convert params to supported variable types:
params = tuple([ convert_to_supported_type(i) for i in params ])
#MySQL and sqlite use differetn syntax:
if connect_to_server == True :
null_string = '%s'
#Make string of ?'s of the right length for insertion into the table:
for i in range(len(params)-1):
null_string += ',%s'
cursor.execute("insert into {} values({})".format(table_name,null_string) , params)
else :
null_string = '?'
for i in range(len(params)-1):
null_string += ',?'
cursor.execute("insert into {} values({})".format(table_name,null_string) , params)
# Commit the changes to the database:
connection.commit()
# Is it necessary to close the connection every single time:
connection.close()
def Pull_Value_From_Row(database_name,table_name,column_name,row_num,connect_to_server=True) :
"""
Pull a specific property from a given row number.
Parameters
-----------------
database_name : str
file path to the database
table_name : str
name of the table witin the database
column_name : str
Name of the column of interest
row_num : int
row number. Note that pythonic convention starts
list at entry 0 while SQL starts tables at row 1.
Returns
-------------
value : variable contained in the specified row of
a given column.
Usage example: (works if the .db file exists).
value = Pull_Value_From_Row("database.db","Results_Table","N",23)
"""
#open the connection to the SQL database:
if connect_to_server==True :
connection, cursor = connect_to_maths_cluster_db()
else :
#Open the connection to the databse:
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
#Pull out the specific value from the chosen row:
cursor.execute("SELECT {} FROM {}".format(column_name,table_name))
rows = cursor.fetchall()
#pdb.set_trace()
#value = cursor.fetchall()[0][0]
value = rows[row_num-1][0]
#If the value is unicode then we convert to a Python string:
#This only matters in Python 2.X. In Python 3 unicode has been
#renamed to string.
"""
See: https://stackoverflow.com/questions/19877306/nameerror-global-name-unicode-is-not-defined-in-python-3
"""
if sys.version_info[0] < 3:
if type(value) == unicode :
value = str(value)
#close the connection:
connection.close()
return value
def get_num_of_rows(database_name,table_name,connect_to_server=False) :
"""
Return the number of rows in a specific table in an SQL
database.
Parameters
---------------
database_name : str
file path to the database
table_name : str
name of the table witin the database
Returns
------------
num_rows : int
Number of rows in the sql table.
"""
#open the connection to the SQL database:
if connect_to_server==True :
connection, cursor = connect_to_maths_cluster_db()
else :
#Open the connection to the databse:
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
cursor.execute("SELECT Count(*) FROM {}".format(table_name) )
num_rows = cursor.fetchall()[0][0]
#close the connection:
connection.close()
return num_rows
def Get_Param_Dicts_to_Sample(param_database,param_table_name,connect_to_server=False) :
"""
Function to read in the input parameters for simulations
from a table.
Parameters
----------------
parameter_database : str
path to the database containing a table of parameters.
Returns
--------------
parameter_dict_list : list of dict
List of dictionaries containing the parameters to sample.
Keys are the variable names and values are the corresponding
values of the variable to sample.
e.g { 'N' : 1000 , 'r' : 0.1 , 'd' : 2 , 'boundary' : 'P' }
"""
#Empty arrays to store the output:
parameter_dict_list = [ ]
num_of_rows = get_num_of_rows(param_database,param_table_name,connect_to_server=connect_to_server)
for row_num in range(num_of_rows) :
#Empty dictionary:
Input_Param_Dict = {}
#Loop through the different input parameter names:
for c_name in {'N','r','d','boundary','degree_scaling_parameter'} :
Input_Param_Dict[c_name] = Pull_Value_From_Row(param_database,param_table_name,c_name,row_num+1,connect_to_server=connect_to_server)
parameter_dict_list.append(Input_Param_Dict)
return parameter_dict_list
|
7ba0531979d8aed9f9af85d74a83cd2b5120426f | PythonTriCities/file_parse | /four.py | 637 | 4.3125 | 4 | #!/usr/bin/env python3
'''
Open a file, count the number
of words in that file using a
space as a delimeter between character
groups.
'''
file_name = 'input-files/one.txt'
num_lines = 0
num_words = 0
words = []
with open(file_name, 'r') as f:
for line in f:
print(f'A line looks like this: \n{line}')
split_line = line.split()
print(f'A split line looks like this: \n{split_line}')
length = len(split_line)
print(f'The length of the split line is: \n{length}')
words.append(length)
print(f'Words now looks like this: \n{words}')
print(f'Number of words: \n{sum(words)}')
|
3dedca2b831eb13b40642a06b8284c039a463a37 | ICHI18/flask-web | /instance/create_booktable.py | 343 | 3.640625 | 4 | import sqlite3
DROP_BOOKS = "DROP TABLE IF EXISTS books"
CREATE_BOOKS = '''CREATE TABLE books(
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
author TEXT,
cover TEXT DEFAULT 'book.png' )'''
conn = sqlite3.connect('bookdb.sqlite3')
c = conn.cursor()
c.execute(DROP_BOOKS)
c.execute(CREATE_BOOKS)
conn.commit()
conn.close()
|
bf14268ceecf09e75939e019e52643814a47dd3e | running-on-sunshine/guess-the-number | /random-num.py | 852 | 4.03125 | 4 | from random import randint
def replay():
# For Python 3: change line below to try_again = input("Try again? (y/n) ")
try_again = raw_input("Try again? (y/n) ")
if try_again == "y":
play_game()
elif try_again == "n":
print("Thanks for playing!")
else:
print("Sorry, I did not understand your response.")
replay()
def play_game():
random_number = randint(1, 10)
guesses_left = 3
print("Guess the Random Number")
print("-----------------------")
print("Try to correctly guess the random number (1 to 10) in 3 tries.")
while guesses_left > 0:
guess = int(input("Your guess: "))
if guess == random_number:
print("You win!")
break
guesses_left -= 1
else:
print("You lose.")
replay()
play_game()
|
07cab18133c3063ca543a93eef35ddfd0aaff741 | YasinMahdizadeh/Codeforces | /1325/C.py | 984 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[83]:
n = int(input())
edges = []
degrees = [0]
for i in range(n):
degrees.append(0)
# In[84]:
output = []
for i in range(n-1):
output.append(-1)
# In[85]:
def d3():
d3_vertex = 0
for i in range(n+1):
if ( degrees[i] > 2 ):
d3_vertex = i
return d3_vertex
# In[86]:
for i in range (n-1):
inp = input().split()
inp = [int(i) for i in inp]
inp.sort()
edges.append(inp)
degrees[inp[0]]= degrees[inp[0]] +1
degrees[inp[1]]= degrees[inp[1]] +1
# In[91]:
f = d3()
if (f > 0):
u = 0;
for i in range(n-1):
if(edges[i][0]==f or edges[i][1]==f):
output[i] = u
u = u+1
for i in range(n-1):
if(output[i]==-1):
output[i] = u
u = u+1
for i in range(n-1):
print(output[i])
else:
for i in range(n-1):
print(i)
# In[ ]:
|
3ac5d4343cc341bc6c517d08fcff1ae5012f58ea | cmpmohan/python | /forloop/for.py | 233 | 3.6875 | 4 |
Write a Python program to construct the following pattern
`*`
`* *`
`* * *`
`* * * *`
`* * * * *`
`* * * *`
`* * *`
`* *`
`*`
Solution:
for i in range(1,6):
print('*' * i)
for l in range(1,6):
print('*' * (5-l) )
|
231bdad8f20bbdf5df6096884b58e388bc66d641 | michelleweii/DataStructure-Algorithms | /5-1.排序与搜索.py | 5,339 | 3.765625 | 4 | # 冒泡排序
# 外层循环控制走多少次
# 内层循环控制从头走到尾
def bubble_sort(alist):
"""冒泡排序"""
n = len(alist)
for j in range(n-1):
# j是[0,1,2,3,...,n-2]
count = 0
for i in range(0,n-1-j):
# 班长从头走到尾
if alist[i]>alist[i+1]: # 升序
alist[i],alist[i+1]=alist[i+1],alist[i]
if 0==count: # 如果没有进行交换(代码优化),变成O(n)--内层循环走一遍
return
# i: 0~n-2 range(0,n-1) j=0
# i: 0~n-3 range(0,n-1-1) j=1
# i: 0~n-4 range(0,n-1-2) j=2
# j=n i range(0,n-1-j)
# # 冒泡方法二:
# for j in range(len(alist)-1,0,-1):
# # j是[n-1,n-2,n-3,n-4,...]
# for i in range(j):
# 选择排序———认为数组有两部分,前一部分是有序的,后一部分是无序的(操作后半部分)
# 遍历一遍,找到最小值,和无序部分的第一个值交换,然后将这个值加入有序部分
def select_sort(alist):
"""选择排序"""
n = len(alist)
for j in range(n-1): # j:0~n-2,先看内层循环
min_index = j
for i in range(j+1, n):
if alist[min_index]>alist[i]:
min_index=i
# 找到最小值的下标之后,进行交换
alist[j],alist[min_index]=alist[min_index],alist[j]
# 插入算法———拿无序序列的第一个元素,和前面有序序列进行比较。(操作前半部分)
def insert_sort(alist):
"""插入排血"""
n=len(alist)
for j in range(1,n):
# i=[1,2,3, ... ,n-1]
# i 代表内层循环起始值
i=j
# 执行从右边的无序序列中取出第一个元素,即i位置的元素,然后将其插入到前面的正确位置中。
while i>0:
# i=j j-1 j-2 ... 1
if alist[i]<alist[i-1]:
alist[i],alist[i-1]=alist[i-1],alist[i]
i-=1
else: # 优化 O(n)
break
# 希尔排序__插入算法的改进版本gap=1时
def shell_sort(alist):
n = len(alist)
gap = n // 2 # 起始从gap开始的
# 4,2,1 或者9,6,1,如何达到最优? 数学知识,不做研究
# gap 变化到0之前,插入算法的执行次数
while gap >= 1:
# 希尔与普通的插入算法的区别就是gap步长
for j in range(gap,n):
# 所有子序列的所有元素
i = j
while i > 0:
# 内循环执行的是:插入算法的比较和交换
if alist[i] < alist[i-gap]:
alist[i], alist[i - gap] = alist[i - gap], alist[i]
i -= gap
else:
break
# 缩短gap步长
gap //= 2
# 快速排序
def quick_sort(alist, first, last):
"""快速排序"""
if first >= last:
# 传进来只有一个元素时
return
mid_value = alist[first]
low = first
high = last
while low < high:
# high 左移
while low<high and alist[high] >= mid_value:
high -= 1
alist[low] = alist[high]
while low<high and alist[low]<mid_value:
low+=1
alist[high]=alist[low]
# 从循环退出时,low==high
alist[low]=mid_value
# 对low左边的列表执行快速排序
quick_sort(alist,first,low-1)
# 对low右边的列表执行快速排序
quick_sort(alist,low+1,last)
# 归并排序
# 快速排序是在本身的基础上进行操作的,归并排序是在已拆分的list上做操作
def merge_sort(alist):
"""归并排序"""
n = len(alist)
if n <= 1:
# 将列表拆分成最后1个1个的时候,只要返回1个元素,1个元素就好
return alist
mid = n//2
# left 采用归并排序后形成的有序的新的列表
left_li = merge_sort(alist[:mid])
# right 采用归并排序后形成的有序的新的列表
right_li = merge_sort(alist[mid:])
# 将两个有序的子序列合并为一个新的整体
# merge(left,right)
left_pointer,right_pointer = 0,0
result = []
while left_pointer<len(left_li) and right_pointer<len(right_li):
# left_pointer,right_pointer都指在当前这一半中的第一个元素
if left_li[left_pointer] < right_li[right_pointer]:
# 合并的时候,哪个元素小,就将哪个元素追加到合并的list中
result.append(left_li[left_pointer])
left_pointer += 1
else:
result.append(right_li[right_pointer])
right_pointer += 1
# 退出循环时,代表left_pointer, right_pointer有一个走到当前list的末尾,
# 但另一个没走到末尾,需要整体追加到合并后的元素中
result += left_li[left_pointer:]
result += right_li[right_pointer:]
return result
# 归并排序,拆分不消耗时间复杂度
# 在合并的时候,由于有元素的比较,然后横向合并时,每一次都是n次;
if __name__ == '__main__':
li = [64,21,22,9,5]
# bubble_sort(li)
# select_sort(li)
# insert_sort(li)
# shell_sort(li)
# quick_sort(li,0,len(li)-1)
print(merge_sort(li)) # [5, 9, 21, 22, 64]
print(li) # [64, 21, 22, 9, 5],归并的时候这种结果 |
aa47260420ce65f1e5b618416186ae42611c3466 | HangLuis/machine_learning | /E2_LinearRegression.py | 1,239 | 3.6875 | 4 | #分别用最小二乘法和Sklearn包实现线性回归
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
A = 2
B = 3
#生成两个100行1列的矩阵
xArr = np.random.randint(100, size=(100, 1))
eArr = np.random.randint(200, size=(100, 1))
#定义yArr
yArr = A + B * xArr + eArr
#保存为Excel文件,分别保存为X_data和Y_data列,并从excel文件读取数据
data = np.c_[xArr, yArr]
save = pd.DataFrame(data, columns=["x_data", "y_data"])
save.to_excel("Out.xls", index=False) #index = False
out = pd.read_excel("Out.xls")
print(out)
#最小二乘法
x_b = np.c_[xArr, np.ones((100, 1), int)]
w_best = (np.linalg.inv(x_b.T.dot(x_b))).dot(x_b.T).dot(yArr)
y_result = np.dot(x_b, w_best) #x_b
#sklearn
regr = LinearRegression().fit(xArr, yArr)
#解决标题中文乱码
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
#绘图
plt.figure()
#-----------------
plt.subplot(1, 2, 1)
plt.title('最小二乘法')
plt.scatter(xArr, yArr)
plt.plot(xArr, y_result, 'r')
#-----------------
plt.subplot(1, 2, 2)
plt.title('Sklearn')
plt.scatter(xArr, yArr)
plt.plot(xArr, regr.predict(xArr), 'g')
#-----------------
plt.show()
|
46aeda1658a8c9463e6f9e369e4c6cadcbff4c1f | Yukiya025/legendary-octo-waddle | /20180926IR.py | 466 | 3.953125 | 4 | # -*- coding: utf-8 -*-
# ↑ This is for recognising Japanese letters in .py file.
"""
Puzzle 21
id 76
"""
def ping(i):
if i > 0:
return pong(i - 1)
return "0"
def pong(i):
if i > 0:
return ping(i - 1)
return "1"
print(ping(29)) # 1
print(ping(10)) # 0
print(pong(29)) # 0
print(pong(10)) # 1
print("Me (*´∀`*)oo0(So the answer will be different by given numbers are odd or not and by which function is designated in print())")
|
e1c9220ec6a8131ccc49023b2c1ba1e5b8d7eb7b | ilyes42/Python-3-DES-algorithm | /test.py | 537 | 4 | 4 | from des64v1 import cipher, reverse_cipher, tobits, frombits
text = 'BONJOUR!'
key = 'aa00df8'
print('encryption key: ', key)
print('text before encryption: ', text)
bin_text = tobits(text)
bin_key = tobits(key)
print('#### CIPHERING ####')
bin_result = cipher(bin_text, bin_key)
result = frombits(bin_result)
print('text after encryption: ', result)
print('#### DECIPHERING ####')
bin_text2 = reverse_cipher(bin_result, bin_key)
text2 = frombits(bin_text2)
print('text after deciphering: ', text2)
input()
|
a448f85c1c93a99ea4487e9d0a2285d712fed13f | benmichener14/MCLA_Python | /Exam_6/Clue.py | 2,215 | 3.953125 | 4 | #************************************************
# Ben Michener
# 4/30/2017
# Intro to Python
# Exam 6 (Clue.py)
#************************************************
import Epic
#************************************************
# Removes a selected term from the appropriate
# list. Returns altered list.
#************************************************
def removeTerm(clue, possible):
term = Epic.userString("Enter the %s that was not involved with the murder: (%s)" % (clue, possible)).lower()
if term in possible:
possible.remove(term)
return possible
#************************************************
# Loops through each list and provides the number
# of different combinations. When there is only
# one combination, then it displays what it is.
#************************************************
def search(people, weapons, rooms):
i = 0
for p in people:
for w in weapons:
for r in rooms:
i = i + 1
if i == 1:
print "There's only one possibility! It was %s in the %s with a %s!" %(p, r, w)
return i
else:
return i
#************************************************
# Assists the user in discovering who commited
# murder. All people, weapons, and rooms from the
# original game of clue are included.
#************************************************
def main():
people = ["miss scarlett", "colonel mustard", "mrs. white", "mr. green", "mrs. peacock", "professor plum"]
weapons = ["candlestick", "knife", "lead pipe", "revolver", "rope", "wrench"]
rooms = ["conservatory", "lounge", "kitchen", "library", "hall", "study", "ballroom", "dining room", "billiard room"]
i = 0
while i != 1:
clue = Epic.userString("Is the clue about a person (p), a weapon (w), or a room (r)").lower()
if clue == "p":
people = removeTerm("person", people)
elif clue == "w":
weapons = removeTerm("weapon", weapons)
elif clue == "r":
rooms = removeTerm("room", rooms)
i = search(people, weapons, rooms)
if i != 1:
print "There are %s possibilities left." % i
main() |
51ee45dc106e02bc975a25dde40fb7962b857e33 | benmichener14/MCLA_Python | /RubiksCube.py | 2,540 | 4 | 4 | #************************************************
# Ben Michener
# 2/16/2017
# Intro to Python
# Exam 2 (RubiksCube.py)
#************************************************
import Epic
#************************************************
# Reads the specified file (filename) and returns a dictionary
# whose keys are names and whose values are the times
# taken to solve a rubiks cube
#************************************************
def readFile(fileName):
d = {}
for line in open(fileName):
temp = line.split(",")
name = temp[0]
d[name] = float(temp[1].strip())
return d
#************************************************
# Takes a dictionary (d) and separates its keys into separate
# lists based on the size of the values they hold
#************************************************
def sortTimes(d):
places = {"Cube Head": [], "Square Master": [], "Advanced Twister": [], "Intermediate Turner": [], "Average Mover": [], "Pathetic" : []}
for name in d:
if d[name] < 10:
places["Cube Head"].append(name)
elif d[name] < 20:
places["Square Master"].append(name)
elif d[name] < 30:
places["Advanced Twister"].append(name)
elif d[name] < 40:
places["Intermediate Turner"].append(name)
elif d[name] < 60:
places ["Average Mover"].append(name)
else:
places["Pathetic"].append(name)
return places
#************************************************
# Takes a dictionary (d) and prints each of the values held in the
# list under each key
#************************************************
def printValues(d):
print "Cube Head (0-9.99):"
for name in d["Cube Head"]:
print "\t %s" % name
print "Square Master (10-19.99):"
for name in d["Square Master"]:
print "\t %s" % name
print "Advanced Twister (20-29.99):"
for name in d["Advanced Twister"]:
print "\t %s" % name
print "Intermediate Turner (30-39.99):"
for name in d["Intermediate Turner"]:
print "\t %s" % name
print "Average Mover (40-59.99):"
for name in d["Average Mover"]:
print "\t %s" % name
print "Pathetic (60 and beyond):"
for name in d["Pathetic"]:
print "\t %s" % name
#************************************************
# Runs appropriate parts of code
#************************************************
def main():
d = readFile("RubiksTimes.txt")
places = sortTimes(d)
printValues(places)
main() |
8b94964cfebbe218e6e048fb10fe8723fb42f856 | mossytreesandferns/PythonPrograms | /PythonGenerateRandNum.py | 566 | 3.71875 | 4 | import random
# .random()
for x in range(5):
print(random.random()) #.random() returns float betw 0 and 1
# .randint()
for x in range(5):
print(random.randint(10,30))
# Choosing from random list
pets = ['turtle','frog','mantis','cat','bees']
first_feed = random.choice(pets)
print(first_feed)
# Create random die-roller object
import random
class Dice:
def dice(self):
face1 = random.randint(1,7)
face2 = random.randint(1,7)
return face1, face2
current_roll = Dice()
print("You rolled " + str(current_roll.dice()))
|
dd5332cdf05ca677a9514d6c6c0d5f125492c79d | mossytreesandferns/PythonPrograms | /PythonLinkedLists.py | 4,456 | 4.15625 | 4 | """Linked Lists"""
# data structures of linked lists are called nodes
class node:
def __init__(self, data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
current = self.head
while current.next != None:
current = current.next
current.next = new_node
def length(self):
current = self.head
total = 0
while current.next != None:
total += 1
current = current.next
return total
def display(self):
elements = []
current_node = self.head
while current_node.next != None:
current_node=current_node.next
elements.append(current_node.data)
print(elements)
def get(self, index): #iterate over
if index >= self.length():
print("Error: Index out of range")
return None
current_index =0
current_node = self.head
while True:
current_node = current_node.next
if current_index == index:
return current_node.data
current_index += 1
def erase(self, index): # erase function
if index >= self.length():
print("Error: Index out of range")
return
current_index = 0
current_node = self.head
while True:
last_node = current_node
current_node = current_node.next
if current_index == index:
last_node.next = current_node.next
return
current_index += 1
my_list = linked_list()
my_list.display()
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
my_list.display()
print("element at second index: %d" % my_list.get(2))
my_list.erase(1)
my_list.display()
"""Double linked lists"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
if self.head == None:
new_node = Node(data)
new_node.prev = None
self.head = new_node
else:
new_node = Node(data)
cur = self.head
while cur.next:
cur = cur.next
cur.next = new_node
new_node.prev = cur
new_node.next = None
def prepend(self, data):
if self.head == None:
new_node = Node(data)
new_node.prev = None
self.head = new_node
else:
new_node = Node(data)
self.head.prev = new_node
new_node.next = self.head
self.head = new_node
new_node.prev = None
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
def add_after_node(self, key, data):
cur = self.head
while cur:
if cur.next is None and cur.data == key:
self.append(data)
return
elif cur.data == key:
new_node = Node(data)
nxt = cur.next
cur.next = new_node
new_node.next = nxt
new_node.prev = cur
nxt.prev = new_node
cur = cur.next
def add_before_node(self, key, data):
cur = self.head
while cur:
if cur.prev is None and cur.data == key:
self.prepend(data)
return
elif cur.data == key:
new_node = Node(data)
prev = cur.prev
prev.next = new_node
cur.prev = new_node
new_node.next = cur
new_node.prev = prev
cur = cur.next
dLinklist = DoublyLinkedList()
dLinklist.append(1)
dLinklist.append(2)
dLinklist.append(3)
dLinklist.append(4)
dLinklist.print_list()
dLinklist.add_before_node(1,111)
dLinklist.add_before_node(2,112)
dLinklist.add_before_node(4,114)
dLinklist.add_after_node(1,11)
dLinklist.add_after_node(2,12)
dLinklist.add_after_node(4,14)
dLinklist.print_list()
dLinklist.prepend(0)
dLinklist.print_list()
dLinklist.prepend(5)
dLinklist.print_list()
|
0c79eb09eecb757788919268ba1c70b28f32542c | mossytreesandferns/PythonPrograms | /PythonBinarySearchTree.py | 2,535 | 3.96875 | 4 | """Binary Search Tree and Binary Search Tree"""
# space O(n), time avg worst O(nlogn) O(n)
class node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class binary_search_tree:
def __init__(self):
self.root = None
def insert(self, data):
if self.root == None:
self.root = node(data)
else:
self._insert(data,self.root)
def _insert(self, data, current_node):
if data < current_node.data:
if current_node.left == None:
current_node.left = node(data)
else:
self._insert(data,current_node.left)
elif data > current_node.data:
if current_node.right == None:
current_node.right = node(data)
else:
self._insert(data, current_node.right)
else:
print("Value is already in tree.")
def print_tree(self):
if self.root != None:
self._print_tree(self.root)
def _print_tree(self, current_node):
if current_node != None:
self._print_tree(current_node.left)
print(str(current_node.data))
self._print_tree(current_node.right)
def height(self):
if self.root != None:
return self._height(self.root, 0)
else:
return 0
def _height(self, current_node, current_height):
if current_node == None:
return current_height
left_height = self._height(current_node.left, current_height + 1)
right_height = self._height(current_node.right, current_height + 1)
return max(left_height,right_height)
def search(self,data):
if self.root != None:
return self._search(data, self.root)
else:
return False
def _search(self,data,current_node):
if data ==current_node.data:
return True
elif data < current_node.data and current_node.left != None:
return self._search(data,current_node.left)
elif data > current_node.data and current_node.right != None:
return self._search(data,current_node.right)
return False
tree = binary_search_tree()
tree.insert(3)
tree.insert(2)
tree.insert(5)
tree.insert(8)
tree.insert(1)
tree.insert(4)
tree.insert(30)
tree.insert(22)
tree.insert(17)
tree.insert(14)
tree.insert(7)
tree.print_tree()
print(tree.height())
print(tree.search(29))
print(tree.search(17))
|
5d67e1df54ee08cb037dc74bc2cc993057c1eb69 | mossytreesandferns/PythonPrograms | /CrawlerWikipedia.py | 1,987 | 3.546875 | 4 | import csv
import os
import requests
import bs4
from bs4 import BeautifulSoup
"""Get Prominent Cajun Fiddlers"""
def result_page_spider():
url = 'https://en.wikipedia.org/wiki/Cajun_fiddle'
source_code = requests.get(url)
source_text = source_code.text
soup = BeautifulSoup(source_text,"lxml")
header = soup.find("span", {'id':'Prominent_proponents_of_the_style'})
unordered = header.parent.find_next_sibling("ul")
link_list = []
for link in unordered.find_all('a'):
fiddler_name = link.string
fiddler_link = "https://en.wikipedia.org/wiki/Cajun_fiddle" + link.get('href')
link_list.append(fiddler_link)
#print(fiddler_name, fiddler_link)
return link_list
result_page_spider()
"""Return Table of information"""
def individual_fiddler_data(fiddler_list):
header_list=[]
for link in fiddler_list:
source_code = requests.get(link)
source_text = source_code.text
soup = BeautifulSoup(source_text,'lxml')
header = soup.find('h1')
text = header.text
header_list.append(text)
header_list=list(header_list)
#print(text)
#print(header_list)
return header_list
individual_fiddler_data(result_page_spider())
# Write to csv
def write_csv(list_of_items):
with open('cajun_fiddlers.csv', mode='w') as fiddle_file:
fiddle_writer = csv.writer(fiddle_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
fiddle_writer.writerows([row] for row in list_of_items)
write_csv(individual_fiddler_data(result_page_spider()))
# Check to make sure that csv was written correctly
import pandas as pd
data = pd.read_csv('cajun_fiddlers.csv')
print(data.head())
# Prevent duplicates
from more_itertools import unique_everseen
with open('cajun_fiddlers','r') as fiddlers, open('cajun_fiddlers2.csv','w') as current_file:
current_file.writelines(unique_everseen(fiddlers)) |
2e5e29bf9bbfa97839fcad012628cd8e06659311 | JowitaKK/python | /function_if_statement.py | 747 | 4.0625 | 4 | def say_hi(name, age):
print("Hello " + name + " you are " + str(age))
print("Top")
say_hi("Jov", 35)
print("Button ")
#=========return function =============
def cube(num):
return num*num*num
result = cube(4)
print(result)
#============if statement=============
is_male = True
is_tall = True
if is_male
print("You are a tall male")
elif is_male and not (is_tall):
print("You are not a male but are tall")
else:
print("You are not a tall man ")
#===========comparisons================
def max_num(num1, num2, num3)
if num1 >= num2 and num1 >= num3: # if "dog" == "dog"
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(20, 230, 3))
|
5cf02b1cba3f8924ad3e40440a13f0d09d455d9e | JowitaKK/python | /loops.py | 1,331 | 4.03125 | 4 | # for loop
# for x in range (1,10):
# print(x)
# print(x*x)
for letter in "coffee": # for in - const, letter- any varriable name
print(letter)
for num in range (10,20,2): # its exclusive does not print 20
print(num)
for num in range(0,100,5):
print(num)
#=========Exercises=================
# 1) print odds number in range 10 20 (is explusive remember has to be 21)
x = 0
for n in range(10,21):
if n % 2 !=0:
x += n
# 2) cleaning your room
times = input ("How many time do I have to tell You ?")
times = int(times)
for time in range(times):
print(f"time {time+1}: Clean up Your room") # +1 to not to print 0
# 3) loop through numbers 1-20 (with 20) /4, 12 print (is unlucky) for even numbers = even , for odds = odd
for num in range(1,21):
if num == 4 or num ==13:
print(f"{num} is unlucky")
elif num % 2 == 0: # for odd num % 2 == 1:
print("f{num} is even")
else:
print("f{num} is odd")
# while loops
#1)
msg = input ("what was the secret password?")
while msg != "banana ": # which should be true
print("Wrong")
msg = input("what is the secret password?")
print("Correct")
#2) print range(1,11)
num = 1
while num < 11:
print(num)
num += 1 # print and stop loop // to do even num += 2
|
45eea610ac318a73b71a21132ef3213fe9185666 | eviss/ChangeAndCode | /python_intro.py | 282 | 3.953125 | 4 | """ name = 'onja'
if name == 'ola':
print('Hey, ola')
elif name == 'onja':
print('Hey, onja')
else:
print('Hey, anything')
def hi(name):
print('hi ' + name + '!')
girls = ['ra', 'liliy', 'You']
for name in girls:
hi(name)
print('next')
"""
for i in range(1,7):
print(i)
|
b236f90cf61d11b343c31e2c0ee3b0b900c98dfa | ezequielpilcsuk/Paradigmas | /python/atividade2/Organismo.py | 1,420 | 3.796875 | 4 | class Organismo:
def __init__(self, position, size):
self.position = position
self.size = size
class Parede_celular:
def __init__(self, gram):
self.gram = gram
class Despesa:
def __init__(self, upkeep):
self.upkeep = upkeep
class Cachorro(Organismo, Despesa):
def __init__(self, position, size, cor_pelo, upkeep):
Organismo.__init__(self, position, size)
Despesa.__init__(self, upkeep)
self.cor_pelo = cor_pelo
@staticmethod
def latir():
print('woof')
# class Boxer(c)
class Celula(Organismo):
def __init__(self, position, size, kind):
Organismo.__init__(self, position, size)
self.kind = kind
self.parede_celular = Parede_celular('gram+')
def fagocitose(self, celula):
print('Fagocitei uma celula de {0} micrômetros'.format(celula.size))
import abc
class Shape(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def method_to_implement(self, input):
return
def main():
bacteria1 = Celula('chão', .5, 'Procarionte')
bacteria2 = Celula('chão', .3, 'Procarionte')
print('Eu sou {1} e estou no {0}.'.format(bacteria1.position, bacteria1.kind))
bacteria2.fagocitose(bacteria1)
bob = Cachorro('chão', 10, 'branco', 200)
Cachorro.latir()
shape = Shape()
shape.method_to_implement(2)
if __name__ == "__main__":
main() |
a28cd468d0a50cd0cb34459672512a51625e3e17 | jamwal-sahil/MOJO_Work | /MOJO_CLI/MojoSwitch.py | 1,579 | 4.09375 | 4 |
a=str(input("Enter the Client MAC Address: "))
x='Y'
while x.upper()=='Y':
b=int(input(''' Select operation
1) Display SSID
2) Dispaly User Session Duration
3) Display Smart Device Type
4) Dispaly Local Time Zone
5) Privacy ALert! Users Domain Accessed
6) Dispalay User Data Transfer From Device (MB) UPLINK
7) Display Data Transfer To Device (MB) DOWNLINK
8) Display Various Analytical Graphs '''))
if b==1:
print('Displaying SSIDs corresponding to given MAC Address')
import function1
function1.fun(a)
elif b==2:
print('Displaying User Session Duration corresponding to given MAC Address')
import function2
function2.fun(a)
elif b==3:
print('Displaying Smart Device Type corresponding to given MAC Address')
import function3
function3.fun(a)
elif b==4:
print('Displaying Local Time Zone corresponding to given MAC Address')
import function4
function4.fun(a)
elif b==5:
print('Displaying Domain Accessed corresponding to given MAC Address')
import function5
function5.fun(a)
elif b==6:
print('Displaying UPLINK(Bytes) corresponding to given MAC Address')
import function6
function6.fun(a)
elif b==7:
print('Displaying DOWNLINK(Bytes) corresponding to given MAC Address')
import function7
function7.fun(a)
elif b==8:
print('Displaying Various Analytical Graphs')
import function8
function8.fun()
else: print('INVALID ENTRY!!!')
x=str(input('Do you wnat to continiue(Y or N)').upper())
if(x=='N'):
break;
|
5f99abdca68c86b2581b0718a4a6742d38fb2a8c | DaphneKeys/Python-Projects- | /fantasygameinventory.py | 933 | 4 | 4 | #!Python3
#This program display the list of keys and values of stuff, inv and dragonLoot
#and sum the total number of items
#Output:-
# Inventory:
# gold coin 45
# rope 1
# dagger 1
# ruby 1
# Total number of items: 48
stuff = {'rope' : 1, 'torch' : 6,'gold coin':42, 'dagger' : 1, 'arrow' : 12}
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(inventory):
print('Inventory:')
total = 0
for a,b in inventory.items():
print(a,b)
total += b
print('Total number of items: '+str(total))
def addToInventory(inventory, addedItems):
for c in addedItems:
if c not in inventory.keys():
inventory[c] = 0
for a,b in inventory.items():
inventory[a] += addedItems.count(str(a))
return inventory
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
|
86197f1e8ce174dca9be4a07d41bdadb38d2efbd | DaphneKeys/Python-Projects- | /guessthenumber.py | 932 | 4.09375 | 4 | import random
print('Hello. what is your name')
name = input()
secretnumber = random.randint(1,20)
print('Well, '+ name + ' ,I am thinking of a number between 1 to 20')
for guesses in range(1,7): #guess 6 times
print('Take a guess')
number = int(input())
if secretnumber < number:
print('Too high')
if number >= 21: #if number is more than 20
print('I am thinking between 1 to 20')
elif secretnumber > number:
print('Too low')
if number <= -1: #if number is negative
print('No negative number. I am thinking between 1 to 20')
else:
print('you guessed right. I was thinking of ' + str(secretnumber))
break
if number == secretnumber:
print('Good job, ' +name+ ' .You guessed my number in '+str(guesses))
elif number != secretnumber:
print('Too bad. The number I was thinking of is ' +str(secretnumber))
|
35ad52319d07ff1cb2f22e56d682eba934bf6680 | DaphneKeys/Python-Projects- | /looping.py | 1,641 | 3.984375 | 4 | # while Loop
spam = 0
while spam < 5:
print('Hello world!')
spam = spam + 1
print('Example 1')
print('-'*13)
#Repeats until user type in 'your name'
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
print('Example 2')
print('-'*13)
#infinite loop with break
name = ''
while True:
print('Please type your name.')
name = input()
if name == 'your name':
print('Thank you!')
break
print('Example 3')
print('-'*13)
#continue statement
spam = 0
while spam < 5:
spam = spam + 1
if spam == 3: #jumps back to the previous while loop
continue
print('spam is '+str(spam))
print('Thank you!')
break
print('Example 4')
print('-'*13)
#for loop
print('My name is')
for i in range(5): #i is set to 0
print('Jimmy five times '+str(i))
print('Example 5')
print('-'*13)
total = 0
for num in range(101):
total = total + num
print(total)
print('Example 6')
print('-'*13)
#nested loops
#for [first iterating variable] in [outer loop]:
# [do something] #optional
# for [second iterationg variable] in [nested loop]:
# [do something]
#enumerate()
num_list = [1,2,3]
alpha_list = ['a','b','c']
for number in num_list:
print(number)
for letter in alpha_list:
print(letter)
print('-'*13)
example = ['left', 'right','up','down']
for i in range(len(example)):
print(i, example[i])
print('-'*13)
for i, j in enumerate(example):
print(i,j)
new_dictionary = dict(enumerate(example))
print(new_dictionary)
|
f120b6ad66ce4ca0c1a621eab1badd981673c3ac | DaphneKeys/Python-Projects- | /madlibs.py | 1,099 | 3.984375 | 4 | #!python3
#madlibs.py
#Automate the boring stuff with python (Page 195)
file = open('MadLibs.txt')
content = file.read()
print(content)
file.close()
#with open('MadLibs.txt') as text:
# user_input = text.read()
wordssplit = content.split() #['The', 'ADJECTIVE', 'panda', 'walked', 'to', 'the', 'NOUN', 'and', 'then', 'VERB.', 'A', 'nearby', 'NOUN', 'was', 'unaffected', 'by', 'these', 'events.']
wordsDictionary = {k: v for k, v in enumerate(wordssplit)} #retrieve both the index and the value of each item python
#{0: 'The', 1: 'ADJECTIVE', 2: 'panda', 3: 'walked', 4: 'to', 5: 'the', 6: 'NOUN', 7: 'and', 8: 'then', 9:'VERB.', 10: 'A', 11: 'nearby', 12: 'NOUN', 13: 'was', 14: 'unaffected', 15: 'by', 16: 'these', 17: 'events.'}
check_words = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']
for keys, values in wordsDictionary.items():
for cw in check_words:
if cw in values:
print('Enter an {}:'.format(values.lower()))#ADJECTIVE,NOUN,ADVERB,VERB is lowercase
wordsDictionary[keys] = input()
print(' '.join(wordsDictionary.values()))
|
042f8b369d088176061e6466a9ce63966526d2d9 | DaphneKeys/Python-Projects- | /madlibs2.py | 623 | 4.03125 | 4 | content = "The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events."
wordssplit = content.split()
wordsDictionary = {k:v for k,v in enumerate(content)} #same thing as below
#wordsDictionary = {k:v for k,v in k,v in content.items()}
check = ["ADJECTIVE", 'NOUN', 'ADVERB', 'VERB']
for keys,values in wordsDictionary:
for checkspeech in check:
if checkspeech in values:
print('Enter an {}:'.format(values.lower())) #ADJECTIVE,NOUN,ADVERB,VERB is lowercase
wordsDictionary[keys] = input()
print(' '.join(wordsDictionary.values()))
|
4b07473939e5c43965a9a97184fa6432516501c8 | hujialiang2020/mycode | /python/16.py | 100 | 3.6875 | 4 | n=10
sum=0
while n>0:
print(sum,n)
sum=sum+n
n=n-1
print('计算结果为:',sum)
|
112ea8a8d75d2825a3c2d98aea44dd1c03ce5ba5 | hujialiang2020/mycode | /python2/13.py | 144 | 3.734375 | 4 | # while 循环
# 循环变量的初始化
n=100
while n>=0:
if n%2==0:
print(n)
# 控制循环变量变化的语句
n=n-1
|
c57e7eccb38e49f9c7dba68ded38a4bc0bbcc19d | hujialiang2020/mycode | /python/38.py | 322 | 3.703125 | 4 | a=int(input('请输入a:'))
b=int(input('请输入b:'))
c=int(input('请输入c:'))
if a<1:
a=1
if a>10:
a=10
if b<1:
b=1
if b>10:
b=10
if c<2:
c=2
if c>5:
c=5
for x in range(a):
print('我爱爸爸')
for x in range(b):
print('我爱妈妈')
for x in range(c):
print('我是胡嘉亮')
|
e010b2b8375146066b096ec4881a79a638076514 | hujialiang2020/mycode | /python2/27.py | 133 | 3.875 | 4 | a=int(input('请输入一个数字:'))
if a>10:
print('大于10')
elif a<10:
print('小于10')
else:
print('等于10')
|
13d4a11e0e6a2ea3b2675e1e7e6ddfa4e3ce4600 | patranun/bread | /function.py | 227 | 3.90625 | 4 | x = int(input())
y = int(input())
def addnumber(x,y):
print(x+y)
def minus(x,y):
print(x-y)
def multiplier(x,y):
print(x*y)
def division(x,y):
print(x/y)
addnumber(x,y)
minus(x,y)
multiplier(x,y)
division(x,y)
|
d2fd477b8c9df119bccb17f80aceda00c61cd82d | Sai-Sumanth-D/MyProjects | /GuessNumber.py | 877 | 4.15625 | 4 | # first importing random from lib
import random as r
# to set a random number range
num = r.randrange(100)
# no of chances for the player to guess the number
guess_attempts = 5
# setting the conditions
while guess_attempts >= 0:
player_guess = int(input('Enter your guess : '))
# for checking the players guess = the actual number
def check(x):
if player_guess == x:
print('You Won!!')
elif player_guess > x:
print('You are a bit on the higher side of the number, try lower!')
else:
print('Your guess is a bit on the lower side, try higher!')
if guess_attempts > 1:
check(num)
elif guess_attempts == 1:
check(num)
print('This is your last chance, try making most of it.')
else:
print('You Lost')
guess_attempts -= 1
|
7e144bbcfd54941dc83968dd89635b11df61aca4 | Ciro1690/Code-in-Place | /nimm.py | 1,157 | 4.03125 | 4 | """
File: nimm.py
-------------------------
Add your comments here.
"""
def main():
stones = 20
player = 1
while stones > 0:
if player == 1:
print("There are " + str(stones) + " stones left")
choice = int(input("Player " + str(player) + " Would you like to remove 1 or 2 stones? "))
if choice == 1:
stones -=1
elif choice == 2:
stones -=2
else:
print("That is an incorrect choice. Please try again.")
player +=1
elif player == 2:
print("There are " + str(stones) + " stones left")
choice = int(input("Player " + str(player) + " Would you like to remove 1 or 2 stones?"))
if choice == 1:
stones -= 1
elif choice == 2:
stones -= 2
else:
print("That is an incorrect choice. Please try again.")
player-=1
print("Game over. Player " + str(player) + " won.")
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
|
13df5ddbfa73e69d1063d2055d28fd5d448a5509 | ydebaz/python-assignment-2 | /list2/count_evens.py | 102 | 3.546875 | 4 | def count_evens(nums):
q=0
for i in range(len(nums)):
if nums[i]%2==0:
q=q+1
return q
|
34bd11929e6344b5206b63f631d3f5f9cbbac14f | ydebaz/python-assignment-2 | /logic1/caught_speeding.py | 259 | 3.625 | 4 | def caught_speeding(speed, is_birthday):
if is_birthday==True:
if speed <66:
return 0
elif speed<86:
return 1
else :
return 2
else :
if speed <61:
return 0
elif speed<81:
return 1
else :
return 2
|
00e7da3547ed1d65e56f5491737ff0e534035227 | Articate/CodingProblems | /DCP_108.py | 639 | 4 | 4 | '''
Daily Coding Problem #108:
Given two strings A and B, return whether or not A can be shifted some number
of times to get B.
For example, if A is abcde and B is cdeab, return true. If A is abc and B is
acb, return false.
'''
def can_shift(arg1, arg2):
for i in range(len(arg1)):
# Make all iterations here
shifted = arg1[-i:] + arg1[:-i]
if shifted == arg2:
return True
return False
if __name__ == "__main__":
res1 = can_shift("abcde", "cdeab")
res2 = can_shift("abcde", "cddeab")
if res1 == True and res2 == False:
print("Success.")
else:
print("Failed.") |
04878674015c392d7aa3b1d663ce9a031850fa58 | dipin24/create-a-small-function-of-python | /cube.py | 148 | 4.03125 | 4 | def cube(num):
return num * num * num
num = int(input("Enter an any number: "))
cub = cube(num)
print("Cube of {0} is {1}".format(num, cub))
|
66c2f836f47ef7d71aed9d1acfbb87cdb14c2c40 | scxr/foobar-sols.py | /3a.py | 621 | 3.828125 | 4 |
import json
import math
"""
https://en.wikipedia.org/wiki/Partition_(number_theory)
"""
def solution(n):
# pad size
sizearr = n + 1
# create zero-filled multi_arr
multi_arr = [[0 for x in xrange(sizearr)] for n in xrange(sizearr)]
# base value is always skipped after being padded
multi_arr[0][0] = 1
for last in xrange(1, sizearr):
for next in xrange(0, sizearr):
multi_arr[last][next] = multi_arr[last - 1][next]
if next >= last:
multi_arr[last][next] += multi_arr[last - 1][next - last]
return multi_arr[n][n] - 1
print solution(200)
|
9969b290d6177312b7d4ea4513cdd0571490e3ac | Angeloquim/EXP6-Hangaroo | /hangaroo.py | 1,798 | 4.09375 | 4 | def isWordGuessed(secretWord, lettersGuessed):
for x in secretWord:
if x not in lettersGuessed:
return False
def getGuessedWord(secretWord, lettersGuessed):
word = ''
for x in secretWord:
if x in lettersGuessed:
word += x
else:
word += '_ '
return word
def getAvailableLetters(lettersGuessed):
letters = "abcdefghijklmnopqrstuvwxyz"
string = ""
for x in letters:
if x not in lettersGuessed:
string += x
return string
secretWord = "apple"
def hangaroo(secretWord):
print ("Welcome to the game, Hangaroo!")
print ("I'm thinking of a word that is " + str(len(secretWord)) + " letters long.")
lettersGuessed = ''
guessesLeft = 8
print ("------------")
while True:
print ("You have " + str(guessesLeft) + " guesses left.")
print ("Available letters: " + getAvailableLetters(lettersGuessed))
guess = input("Please guess a letter: ")
if guess in secretWord and guess not in lettersGuessed:
lettersGuessed += guess
print ("Good guess: " + getGuessedWord(secretWord, lettersGuessed))
elif guess in lettersGuessed:
print ("Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed))
else:
lettersGuessed += guess
print ("Oops! Not part of the word: " + getGuessedWord(secretWord, lettersGuessed))
guessesLeft -= 1
print ("------------")
if guessesLeft <= 0:
print ("Sorry, You've ran out of guesses. The word was " + secretWord + ".")
break
if guess == secretWord:
print ("Congratulations! You've won!")
break |
d541bf1761124b3aa573557912fd40664afde72f | Diogueira/CursoEmVideoPyton | /desafio 7.py | 174 | 3.90625 | 4 | nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1+nota2)/2
print('A media do aluno foi {:.1f}.'.format(media))
|
54d89873ce83e0bbb946f4f54446db5d08dd5af0 | the-isf-academy/lab-trivia-2021 | /player.py | 694 | 3.96875 | 4 | # player.py
# Author: Emma Brown
# ==================
class Player:
""" Creates a Player object for use in the TriviaGame. Player includes a
name, score, and buzzer, and button.
"""
def __init__(self, name, button, buzzer,led):
self.name = name
self.score = 0
self.buzzer = buzzer
self.button = button
self.led = led
def add_score(self):
self.score += 1
def get_score(self):
return self.score
def get_name(self):
return self.name
def get_buzzer(self):
return self.buzzer
def get_button(self):
return self.button
def get_led(self):
return self.led
|
6513977254d7ef8c8f23a151cea24bfc5ef64de6 | alien19/Classical-Ciphers | /hill.py | 1,743 | 3.9375 | 4 | import numpy as np
def encrypt_hill(plainText, key):
"""
encrypts plaintext with hill cipher method and writes the output in hill_cipher.txt
Args:
plainText(list): list of plaintext in hill_plain.txt file
[each line in the file is a list element]
key(list): hill cipher key matrix
Returns:
cipherText(list): list of ciphertexts opposite to each plaintext
"""
if len(key) == 4:
k = np.array(list(map(int, key))).reshape((2, 2))
r = 2
elif len(key) == 9:
k =np.array(list(map(int, key))).reshape((3,3))
r = 3
cipherText = []
# r = key.shape[0]
for p in plainText:
p = p.replace('\n', '')
p = p.replace(' ', '')
# offset = 65
if p.islower():
offset = 97
elif p.isupper():
offset = 65
else:
p = p.lower()
offset = 97
if r==2 and len(p)%2:
p = p + 'x'
elif r==3:
if len(p)%3==2:
p = p + 'x'
elif len(p)%3==1:
p = p + 'xx'
p_nums = np.fromstring(p, np.uint8) - offset
res_b = b''
for i in range(0, p_nums.shape[0], r):
res = np.dot(k.astype('int32'), p_nums[i:i+r].reshape(-1, 1).astype('int32'))
res = ((res%26) + offset).reshape(-1,).astype('uint8')
res_b = b''.join((res_b, b''.join(res)))
cipherText.append(res_b + b'\n')
if r==2:
with open("hill_cipher_2x2.txt", 'wb') as f:
f.writelines(cipherText)
if r==3:
with open("hill_cipher_3x3.txt", 'wb') as f:
f.writelines(cipherText)
return cipherText |
3221e23e7a757591ed65cd062d9a98e4b680f081 | mhoamedbayoumi/detecting-Fake-News-with-Python | /learn.py | 1,568 | 3.546875 | 4 | #importing important modules that we will need
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import itertools
from sklearn.metrics import confusion_matrix
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.ensemble import RandomForestClassifier
df=pd.read_csv("news.csv")
df.head()
#store feture in variable
text=df['text']
#store label we will predict in variable
labels=df['label']
labels.head()
# split our data to train data and test data
X_train,x_test,y_train,y_test=train_test_split(text,labels,test_size=0.2,random_state=7)
#make object from tfidvectotizer type words english max words 7
tfidf_vectorizer=TfidfVectorizer(stop_words='english', max_df=0.7)
# train the module on the training data
tfidf_train=tfidf_vectorizer.fit_transform(X_train)
tfidf_test=tfidf_vectorizer.transform(x_test)
#Initialize a PassiveAggressiveClassifier
pac=RandomForestClassifier()
#trian y dataset
pac.fit(tfidf_train,y_train)
# what we will pridect
y_pred=pac.predict(tfidf_test)
# compare our pridections to the testset
score=accuracy_score(y_test,y_pred)
print(f'Accuracy: {round(score*100,2)}%')
# print the accuracy 100%
#
#
# lets pridict new information after we train the moudel
input_data = [input()]
vectorized_input_data = tfidf_vectorizer.transform(input_data)
prediction = pac.predict(vectorized_input_data)
print(prediction)
|
dc2468b63209b7c02b3555e9b39ee58b960dca36 | webclinic017/quant-framework | /quant_framework/data_providers/data_provider.py | 592 | 3.734375 | 4 | from abc import ABC, abstractmethod
class DataProvider(ABC):
'''
An abstract class that all data providers must inherit from
Data Providers are intended to be wrappers around vendors that provide daily stock market data
'''
@property
@abstractmethod
def name(self):
pass
@property
@abstractmethod
def documentation_url(self):
pass
@abstractmethod
def fetch_historical_price_data(self, ticker, req_date):
pass
@abstractmethod
def fetch_historical_price_data_range(self, ticker, start, end):
pass
|
8b824f5acd7443f794419c74369f89dcdae6d407 | Yemeen/Kindling | /foldercount.py | 628 | 4 | 4 | import os
def numfold(path):
# path='/home/' + os.getlogin() + '/Code/Kindling/images/'
# path = "./images/"
files = folders = 0
for _, dirnames, filenames in os.walk(path):
# ^ this idiom means "we won't be using this value"
folders += len(dirnames)
return folders
def numfile(path):
# path='/home/' + os.getlogin() + '/Code/Kindling/images/'
files = folders = 0
for _, dirnames, filenames in os.walk(path):
# ^ this idiom means "we won't be using this value"
files += len(filenames)
return files
if __name__ == '__main__':
print("files: "+str(numfile()))
print("folders: "+str(numfold()))
|
dbef91a7ddfd4100180f9208c3880d9311e2c94c | Arlisha2019/HelloPython | /hello.py | 1,319 | 4.34375 | 4 | #snake case = first_number
#camel case =firstNumber
print("Hello")
#input function ALWAYS returns a String data type
#a = 10 # integer
#b = "hello" # String
#c = 10.45 # float
#d = True # boolean
#convert the input from string to int
#first_number = float(input("Enter first number: "))
#second_number = float(input("Enter second number: "))
#third_number = float(input("Enter third number: "))
#number = int("45")
#first_number_as_int = int("45")
#second_number_as_int = int("70")
#some_result = first_number_as_int + second_number_as_int
#result = first_number + second_number + third_number
#result = int(first_number) + int(second_number)
#print(result)
#name = input("Enter your name: ")
#print(name)
#name = "John"
#age = 20
#version = 3.35
# Print will print the value of name variable to tthe screen
#print(name)
#name = "Mary"
#print(name)
#string concatcentration
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
city = input("Enter city: ")
state = input("Enter State: ")
zip_code = input("Enter Zip Code: ")
message = "My name is {0},{1} and I live in {2}, {3}, {4}".format(first_name,last_name,city,state,zip_code)
#message = "My name is " + first_name + ", " + last_name + ", " + " and I live in " + city + ", " + state + " " + zip_code
print(message)
|
9246e299a1f1aa0ba8328fa2b7ab5a5047a70f90 | mokkeee/tddbc5th_python | /grid_points.py | 2,263 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from grid_point import GridPoint
__author__ = 'mokkeee'
class GridPoints(object):
def __init__(self, *args):
if not self.__is_valid_grids(args):
raise ValueError
self.__grids = args
def __contains__(self, item):
if not isinstance(item, GridPoint):
return False
return item in self.__grids
def __len__(self):
return len(self.__grids)
def is_connected_grids(self):
for grid in self.__grids:
if not self.__has_neighbor(grid):
return False
else:
return True
def is_traversal(self):
# if not self.is_connected_grids():
# return False
start_grid = self.__traverse_start_grid()
traversed_grids = [start_grid]
current_grid = start_grid
while not self.__is_traverse_complete(traversed_grids):
next_grid = self.__next_grid(current_grid, traversed_grids)
if next_grid is None:
return False
current_grid = next_grid
traversed_grids.insert(-1, current_grid)
else:
return True
def neighbors(self, grid):
return [x for x in self.__grids if x.is_neighbor(grid)]
def __traverse_start_grid(self):
sorted_grids = sorted(self.__grids, key=lambda x: len(self.neighbors(x)))
return sorted_grids[0]
def __next_grid(self, current_grid, traversed_grids):
neighbors = [x for x in self.neighbors(current_grid) if x not in traversed_grids]
if len(neighbors) == 0:
return None
return neighbors[0]
def __is_traverse_complete(self, traversed_grids):
return len(traversed_grids) == len(self)
def __has_neighbor(self, grid):
neighbors = self.neighbors(grid)
if len(neighbors) == 0:
return False
return True
@staticmethod
def __is_valid_grids(args):
for point in args:
if not isinstance(point, GridPoint):
return False
points_count = len(args)
if len(set(args)) != points_count:
return False
if points_count < 2:
return False
return True
|
c04adc6f367b080a1001447a8186ae0434430735 | wqmeepo/practice-project | /IDLE 学生管理系统/do.py | 4,790 | 3.6875 | 4 | def save(student):
with open('./student.txt', 'a+') as f:
for info in student:
f.write(str(info) + '\n')
def insert():
studentList = []
mark = True
while mark:
init = input('即将开始录入学生信息,输入0回到主界面')
if init == '0':
break
id = input('请输入6位ID(例如000001):')
name = input('请输入姓名(例如0张三):')
english = input('请输入英文成绩(请输入数字):')
python = input('请输入python成绩(请输入数字):')
c = input('请输入c语言成绩(请输入数字):')
if not id or not name or not english or not python or not c:
print("请不要输出空值,请重新输入")
continue
student = {'id': id, 'name': name, 'english': english, 'python': python, 'c': c}
studentList.append(student)
inputMark = input('是否继续输入{y/n}:')
if inputMark == 'y' or inputMark == 'Y':
mark = True
if inputMark == 'n' or inputMark == 'N':
mark = False
save(studentList)
print('学生信息保存完毕!!')
def delete():
mark = True
studentList = []
studentDic = []
show()
while mark:
studentId = input('上列位所有学生信息,请输入要删除的学生id(输入0退出程序):')
if studentId == '0':
break
elif not studentId:
print('不允许输入空值,请重新输入')
continue
else:
with open('./student.txt', 'r') as f:
for info in f.readlines():
info_dic = eval(info)
studentDic.append(info_dic['id'])
if studentId not in studentDic:
print('学生ID不在信息库内,请重新选择')
continue
else:
print('学生ID在信息库内,正在删除,下列为删除后的信息')
with open('./student.txt', 'r') as f:
for info in f.readlines():
info_dic = eval(info)
studentList.append(info_dic)
with open('./student.txt', 'w') as f:
for info in studentList:
if info['id'] != studentId:
f.write(str(info) + '\n')
show()
inputMark = input('删除成功,是否继续删除{y/n}:')
if inputMark == 'y' or inputMark == 'Y':
mark = True
if inputMark == 'n' or inputMark == 'N':
mark = False
def show():
with open('./student.txt', 'r') as f:
for info in f.readlines():
print(info)
def modify():
show()
studentId = input('上列为所有学生信息,请输入要修改的学生id(输入0退出程序):')
studentDic = []
studentList = []
mark = True
while mark:
if studentId == '0':
break
elif not studentId:
print('不允许输入空值,请重新输入')
continue
else:
with open('./student.txt', 'r') as f:
for info in f.readlines():
info_dic = eval(info)
studentDic.append(info_dic['id'])
if studentId not in studentDic:
print('学生ID不在信息库内,请重新选择')
continue
else:
print('学生ID在信息库内,请输入修改后的内容')
name = input('姓名 name = ')
english = input('英语成绩 = ')
python = input('python成绩 = ')
c = input('c语言成绩 = ')
with open('./student.txt', 'r') as f:
for info in f.readlines():
info_dic = eval(info)
studentList.append(info_dic)
with open('./student.txt', 'w') as f:
for info in studentList:
if info['id'] != studentId:
f.write(str(info) + '\n')
elif info['id'] == studentId:
info['name'] = name
info['english'] = english
info['python'] = python
info['c'] = c
f.write(str(info) + '\n')
show()
inputMark = input('删除成功,是否继续删除{y/n}:')
if inputMark == 'y' or inputMark == 'Y':
mark = True
if inputMark == 'n' or inputMark == 'N':
mark = False
def search():
TODO
def sort():
TODO
def total():
TODO
|
2afb37f1e237b6bf7fd1d3eb9e2ed9386b8299ac | thulanimbatha/python_turtle-day-18 | /challenge4.py | 479 | 3.5625 | 4 | import turtle
import random
directions = [0, 90, 180, 270, 360]
tmnt = turtle.Turtle()
tmnt.shape("turtle")
tmnt.pensize(13)
tmnt.speed("fastest")
turtle.colormode(255)
def random_colour():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
for _ in range(100):
tmnt.pencolor(random_colour())
tmnt.forward(40)
tmnt.setheading(random.choice(directions))
screen = turtle.Screen()
screen.exitonclick() |
72562cee1e41dc97927abe5c23ff63f950caae91 | unitogi/20x20DaysOfPython | /Input_output/console.py | 345 | 3.9375 | 4 | """Typecasting and input from console"""
def oddeven(num):
if num%2==0:
print("Even")
else:
print("Odd")
return
def main():
print("running")
n = int(input("Enter a number to check even or odd : "))
print("THIS IS MAIN FUCNTION")
oddeven(num)
if __name__ == ' __main__':
main()
|
8661f7bd1b892e82d69446da6e5fca81eaca79fa | GaganDureja/Algorithm-practice | /Fibonacci.py | 257 | 3.953125 | 4 | #Problem: Implement the function fib(n),\
# which returns the nth number in the Fibonacci sequence, using only O(1) space.
def fib(n):
return 0 if not n else 1 if n==1 else fib(n-1) + fib(n-2)
print(fib(0))
print(fib(5))
print(fib(8)) |
06297a13292f55c548d902be0d153dfebaaa0b68 | GaganDureja/Algorithm-practice | /sum odd,even.py | 205 | 3.828125 | 4 | #Link: https://edabit.com/challenge/5XXXppAdfcGaootD9
def sum_odd_and_even(lst):
return [sum(x for x in lst if x%2==0) ,sum(x for x in lst if x%2)]
print(sum_odd_and_even([1, 2, 3, 4, 5, 6])) |
c091a35ca580e22cd3afdb473422a3832957cdeb | GaganDureja/Algorithm-practice | /recaman sequence.py | 273 | 3.640625 | 4 | #Link: https://edabit.com/challenge/fW52x9Gh5iMKNfWMt
def recaman_index(n):
lst = [0]
while n not in lst:
num1 = lst[-1]-len(lst)
num2 = lst[-1]+len(lst)
lst.append(num1 if num1>=0 and num1 not in lst else num2)
return len(lst)-1
print(recaman_index(7))
|
1c608c7fea6d75023c0533d888e2346f5439d674 | GaganDureja/Algorithm-practice | /Collatz Conjecture.py | 195 | 3.796875 | 4 | #Link: https://edabit.com/challenge/X8fNb5EouWxrMMjZL
def collatz(num):
count = 0
while num!=1:
if num%2:num= num*3 +1
else:num/=2
count+=1
return count
print(collatz(10)) |
30ab7d4ef238c8f6002a85e286e011a4edb2fa23 | GaganDureja/Algorithm-practice | /words to sentence.py | 293 | 3.875 | 4 | #Link: https://edabit.com/challenge/GP6CEr9a5CMqPHY7C
def words_to_sentence(words):
if not words: return ''
words = [x for x in words if x]
l = len(words)
return ''.join(words[x] +(' and ' if x==l-2 else '' if x==l-1 else ', ') for x in range(l))
print(words_to_sentence(None)) |
14b39d2d299b845a4c72dac97f0a2c43f096c6bc | GaganDureja/Algorithm-practice | /find unique.py | 157 | 3.53125 | 4 | #Link: https://edabit.com/challenge/GaXXfmpM72yCHag9T
def unique(lst):
return [x for x in lst if lst.count(x)==1][0]
print(unique([3, 3, 3, 7, 3, 3])) |
8e87f3cbe94c2da7ea76be728727036a07d1311e | GaganDureja/Algorithm-practice | /sum two num.py | 486 | 3.890625 | 4 | #Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
#For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
#Bonus: Can you do this in one pass?
from itertools import combinations as cb
def sum_of_two(lst,k):
return any(sum(x)==k for x in cb(lst,2))
print(sum_of_two([10, 15, 3, 7],17))
print(sum_of_two([10, 15, 3, 2],17))
print(sum_of_two([9, 10, 3, 7],18))
print(sum_of_two([9, 9, 3, 7],18)) |
0b70fa9835857ad1361413bbb6bf73716cbc5ab5 | GaganDureja/Algorithm-practice | /binary search.py | 326 | 3.921875 | 4 | #Link: https://edabit.com/challenge/kKFuf9hfo2qnu7pBe
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def is_prime(primes, num, left=0, right=None):
for x in range(left,len(primes)):
if primes[x]==num:
return 'yes'
return 'no'
print(is_prime(primes, 3)) |
ec80b2382b81b8dd75f638e4f9fe59fc98424c12 | GaganDureja/Algorithm-practice | /mystery challenge.py | 338 | 3.609375 | 4 | #Link: https://edabit.com/challenge/uCKJi6X3KTH9zuSc3
def mystery_func(n):
n=str(n)
res = [n[0]]
for x in range(1,len(n)):
if n[x]==n[x-1]:
res[-1]+=n[x]
else:
res.append(n[x])
return ''.join([''.join([str(len(x)),x[0]]) for x in res])
print(mystery_func(5211255)) |
c0883b467fa9ac0cfce8973582431382784e8958 | GaganDureja/Algorithm-practice | /Unique char.py | 149 | 3.5 | 4 | Link: https://edabit.com/challenge/oTJaJ895ubqqpRPMh
def count_unique(s1, s2):
return len(set(s1+s2))
print(count_unique("apple", "play"))
|
b8a0ee1bbac2ab2947ea33c4d03ec457fe575feb | GaganDureja/Algorithm-practice | /Unique char map.py | 215 | 3.953125 | 4 | #Link: https://edabit.com/challenge/yPsS82tug9a8CoLaP
def character_mapping(txt):
lst = ''
for x in txt:
if x not in lst:
lst+=x
return [lst.index(x) for x in txt]
print(character_mapping("babbcb")) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.