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 |
|---|---|---|---|---|---|---|
bafcfb78e38c42cf6c23be6f509de455a905319b | mezla/6001x | /Part 1/secret_num.py | 685 | 4.09375 | 4 | print 'Please think of a number between 0 and 100!'
epsilon = 1
step = 1
low = 0
high = 100
ans = (high+low)/2
while abs(ans**2-100) >= epsilon:
print 'Is your secret number ' + str(ans) + '?'
info = str(raw_input('Enter \'h\' to indicate the guess is too high. Enter \'l\' to indicate the guess is too low. Enter \'c\' to indicate I guessed correctly. '))
if info == 'c':
print 'Game over. Your secret number was: ' + str(ans)
break
elif info == 'l':
low = ans
ans = (high+low)/2
elif info == 'h':
high = ans
ans = (high+low)/2
else:
print "Sorry, I did not understand your input." |
4a610288128ebf5377b29cba18ea047633b340f5 | mezla/6001x | /Part 1/quiz/p5.py | 693 | 3.984375 | 4 | def laceStrings(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
if not s1 or not s2:
if not s1:
return s2
else:
return s1
lace = ''
count = 0
for char in s1:
try:
lace += s1[count] + s2[count]
except ValueError:
break
else:
count += 1
if count < len(s1):
lace += s1[count:]
elif count < len(s2):
lace += s2[count:]
return lace |
00708ba1d213c584d475ca099e6be832a27fac0c | mezla/6001x | /Part 1/quiz/p7_div_try_2.py | 608 | 3.9375 | 4 | def McNuggets(n):
"""
n is an int
Returns True if some integer combination of 6, 9 and 20 equals n
Otherwise returns False.
"""
x = 1
while True:
if n%20 == 0:
return True
elif n%9 == 0:
return True
elif n%6 == 0:
return True
else:
if (n%20)%9 == 0:
return True
elif (n%20)%6 == 0:
return True
else:
if (n%9)%6 == 0:
return True
else:
return False |
9723db9bc6f9d411d0ae62f525c33a410af9f529 | george-ognyanov-kolev/Learn-Python-Hard-Way | /44.ex44.py | 981 | 4.15625 | 4 | #inheritance vs composition
print('1. Actions on the child imply an action on the parent.\n')
class Parent1(object):
def implicit(self):
print('PARENT implicit()')
class Child1(Parent1):
pass
dad1 = Parent1()
son1 = Child1()
dad1.implicit()
son1.implicit()
print('2. Actions on the child override the action on the parent.\n')
class Parent2(object):
def override(self):
print('PARENT override()')
class Child2(Parent2):
def override(self):
print('CHILD override()')
dad2 = Parent2()
son2 = Child2()
dad2.override()
son2.override()
print('3. Actions on the child alter the action on the parent.\n')
class Parent3(object):
def altered(self):
print('PARENT3 altered()')
class Child3(Parent3):
def altered(self):
print('CHILD BEFORE PARENT altered()')
super(Child3, self).altered()
print('CHILD AFTER altered()')
dad3 = Parent3()
son3 = Child3()
dad3.altered()
son3.altered()
|
04ed69a5fdc6f03188549846aa98dff194753490 | Coder1900/guessing_game | /main.py | 3,089 | 4.15625 | 4 | import random
import my_input_library as myinputs
# creates a random number and asks user to guess it
# the input is the number range to guess_random_number
# output is number of trys
def guess_random_number(upper_limit):
trys = 0
guess = ""
number_generator = random.randint(0, upper_limit)
while guess != number_generator:
#print(number_generator) # debugging message
msg = "Guess the number between 0 - " + str(upper_limit) + ": "
guess = myinputs.get_input(msg)
trys += 1
if guess < number_generator:
print("Incorrect you had to guess a bigger number")
elif guess > number_generator:
print("Incorrect you had to guess a smaller number")
elif guess == number_generator:
print("correct")
score = (f"It took you {trys} attempts to guess the correct number" )
print(score)
return trys
# if user takes more then 9 trys to guess the round ends
if trys >= 9:
return trys
# main function that runs the game
def run_game():
my_high_score = 9 # init the high score to the lowest score
# asks user for game level and checks if it is greater then 0
while 1:
guess_range = myinputs.game_level()
if guess_range > 0:
break
# while the user wants to continue play the game
while 1:
all_time_high_score_of_level = get_high_score(guess_range)
attemps = (guess_random_number(guess_range))
if attemps < my_high_score:
my_high_score = attemps
print(f"Your score is {attemps} and your high score was {my_high_score} ")
if my_high_score < all_time_high_score_of_level:
print(f"You beat the all time high score which was {all_time_high_score_of_level}")
records_high_scores(guess_range, my_high_score)
else:
print(f"Try to beat all time high score which is {all_time_high_score_of_level}")
print("")
print("Do you want to continue or change level or quit? ")
user_continue = input("Please enter continue or change or quit: ")
print("")
if user_continue.lower() == "change":
while 1:
guess_range = myinputs.game_level()
if guess_range > 0:
break
elif user_continue.lower() != "continue":
break
# function that gets high score and returns it
def get_high_score(level):
high_scores_array = myinputs.reads_high_scores()
while 1:
if level == 10:
return high_scores_array[0]
elif level == 25:
return high_scores_array[1]
elif level == 50:
return high_scores_array[2]
# stores the high score in a variable
def records_high_scores(level, high_score):
high_scores_array = myinputs.reads_high_scores()
if level == 10:
high_scores_array[0] = high_score
elif level == 25:
high_scores_array[1] = high_score
elif level == 50:
high_scores_array[2] = high_score
myinputs.stores_high_scores(high_scores_array)
## Main function
print("############################")
print("Welcome to number guessing game")
print("Designed by: Solomon")
print("############################")
print("")
run_game()
|
26c234de72edc6fcfa981194814c814e40bc7bed | chuzhinoves/DevOps_python_HW4 | /6_a.py | 940 | 3.796875 | 4 | """
6. Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
Подсказка: использовать функцию count() и cycle() модуля itertools.
Обратите внимание, что создаваемый цикл не должен быть бесконечным.
Необходимо предусмотреть условие его завершения.
Например, в первом задании выводим целые числа, начиная с 3,
а при достижении числа 10 завершаем цикл.
"""
from itertools import count
import sys
MAX_NUMB = 10
def generator(start):
for i in count(start):
if i > MAX_NUMB:
return
yield i
if __name__ == "__main__":
[print(i) for i in generator(int(sys.argv[1]))] |
fa6e8dd7c6f9f9279cb60f469fbaaf5a2a8bc686 | kritikadusad/AlgorithmsForDNASequencing | /shortest_common_superstring.py | 3,797 | 4.0625 | 4 | import itertools
def overlap(a, b, min_length=3):
""" Return length of longest suffix of 'a' matching
a prefix of 'b' that is at least 'min_length'
characters long. If no such overlap exists,
return 0. """
start = 0 # start all the way at the left
while True:
start = a.find(b[:min_length], start) # look for b's suffx in a
if start == -1: # no more occurrences to right
return 0
# found occurrence; check for full suffix/prefix match
if b.startswith(a[start:]):
return len(a) - start
start += 1 # move just past previous match
def scs(ss):
"""
Returns shortest common superstring of given
strings, which must be the same length
Example 1:
>>> scs(["ABC", "BCA", "CAB"])
'ABCAB'
Example 2:
>>> len(scs(["CCT", "CTT", "TGC", "TGG", "GAT", "ATT"]))
11
"""
shortest_sup = None
all_substrings = set()
for ssperm in itertools.permutations(ss):
sup = ssperm[0] # superstring starts as first string
for i in range(len(ss) - 1):
# overlap adjacent strings A and B in the permutation
olen = overlap(ssperm[i], ssperm[i + 1], min_length=1)
# add non-overlapping portion of B to superstring
sup += ssperm[i + 1][olen:]
if shortest_sup is None or len(sup) < len(shortest_sup):
shortest_sup = sup # found shorter superstring
return shortest_sup # return shortest
def scs_list(ss):
"""
Returns shortest common superstring of given
strings, which must be the same length
Example 1:
>>> scs_list(['ABC', 'BCA', 'CAB'])
3
>>> scs_list(['GAT', 'TAG', 'TCG', 'TGC', 'AAT', 'ATA'])
10
>>> scs_list(["CCT", "CTT", "TGC", "TGG", "GAT", "ATT"])
4
"""
shortest_sup_1 = scs(ss)
all_substrings = {shortest_sup_1}
for ssperm in itertools.permutations(ss):
sup = ssperm[0] # superstring starts as first string
for i in range(len(ss) - 1):
# overlap adjacent strings A and B in the permutation
olen = overlap(ssperm[i], ssperm[i + 1], min_length=1)
# add non-overlapping portion of B to superstring
sup += ssperm[i + 1][olen:]
if len(sup) == len(shortest_sup_1):
shortest_sup = sup # found shorter superstring
all_substrings.add(shortest_sup)
return len(all_substrings)
def readFastq(filename):
sequences = []
with open(filename) as fh:
while True:
fh.readline() # skip name line
seq = fh.readline().rstrip() # read base sequence
fh.readline() # skip placeholder line
qual = fh.readline().rstrip() # base quality line
if len(seq) == 0:
break
sequences.append(seq)
return sequences
reads = readFastq("ads1_week4_reads.fq")
def pick_max_overlap(reads, k):
""" Returns 2 reads with maximum overlap"""
reada, readb = None, None
best_olen = 0
for a, b in itertools.permutations(reads, 2):
olen = overlap(a, b, min_length=k)
if olen > best_olen:
best_olen = olen
reada, readb = a, b
return reada, readb, best_olen
def greedy_scs(reads, k):
"""
Example 1:
>>> greedy_scs(["ABC", "BCA", "CAB"], 2)
'CABCA'
"""
reada, readb, olen = pick_max_overlap(reads, k)
while olen > 0:
reads.remove(reada)
reads.remove(readb)
reads.append(reada + readb[olen:])
reada, readb, olen = pick_max_overlap(reads, k)
return "".join(reads)
print(greedy_scs(reads, 30))
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print("Tests passed.")
|
e5663cb79ea48d897aacc4350443c713dee27d5e | jejakobsen/IN1910 | /week1/e4.py | 773 | 4.15625 | 4 | """
Write a function factorize that takes in an integer $n$, and
returns the prime-factorization of that number as a list.
For example factorize(18) should return [2, 3, 3] and factorize(23)
should return [23], because 23 is a prime. Test your function by factorizing a 6-digit number.
"""
def get_primes(n):
numbers = set(range(n, 1, -1))
primes = []
while numbers:
p = numbers.pop()
primes.append(p)
numbers.difference_update(set(range(p*2, n+1, p)))
return primes
def factorize(n):
P = get_primes(n)
ls = []
while n > 1:
for p in P:
if n%p == 0:
ls.append(p)
n = n/p
break
return ls
print(factorize(921909))
"""
C:\\Users\\jensj\\OneDrive\\Skrivebord\\IN1910\\week1>python e4.py
[3, 23, 31, 431]
""" |
8e1f774d2d8748ae9f0a7707208ebf6e77ca8f7a | Yousab/parallel-bubble-sort-mpi | /bubble_sort.py | 981 | 4.1875 | 4 | import numpy as np
import time
#Bubble sort algorithm
def bubble_sort(nums):
# We set swapped to True so the loop looks runs at least once
swapped = True
while swapped:
swapped = False
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
# Swap the elements
nums[i], nums[i + 1] = nums[i + 1], nums[i]
# Set the flag to True so we'll loop again
swapped = True
# Verify it works
random_list_of_nums = [5, 2, 1, 8, 4]
#User input size
arraySize = input("Please enter array size: ")
#Generate numbers of size n
numbers = np.arange(int(arraySize))
np.random.shuffle(numbers)
print("Generated list of size " + str(arraySize) + " is:" + str(numbers))
#start script with parallel processes
start_time = time.time()
bubble_sort(numbers)
print("\n\n Sorted Array: " + str(numbers))
#End of script
print("\n\n Execution Time --- %s seconds ---" % (time.time() - start_time)) |
213560426ae3dcc15c94f6e262f8a1f5dd34261d | camillemura100t/DevOps_training | /python_training/f_pair_impair.py | 423 | 3.765625 | 4 | #!/usr/bin/env python3.8
#=> module
def pair(valeur1):
if valeur1 % 2 == 0:
return True
def impair(valeur2):
if valeur2 % 2 != 0:
return True
#var1 = int(input("Entrer un nombre entier: "))
#if pair(var1):
# print("La fonction pair retourne True pour la valeur %d" %var1)
#elif impair(var1):
# print("La fonction impair retourne True pour la valeur %d" %var1)
#else:
# print("Error")
|
faa9a84da62da62e5c6b3f9038f71a6b811e0e95 | camillemura100t/DevOps_training | /python_training/boucle_test_vanessa.py | 446 | 3.5625 | 4 | #!/usr/bin/env python3.8
liste_produit = ['chaussure', 'pain', 42, 'chocolat']
taux_tva = 19.6
taux_tva_bas = 5.5
liste_prix = {}
for produit in liste_produit:
if produit == 'pain':
liste_prix[produit] = taux_tva_bas * 10
continue
elif type(produit) != str:
print(type(produit))
print('erreur dans la liste des produits')
break
liste_prix[produit] = taux_tva * 10
print(liste_prix) |
3fb47ab2714c6447b691f3954d9b0a5cfafeea9f | eodenyire/AirBnB_clone-7 | /models/city.py | 469 | 3.5625 | 4 | #!/usr/bin/python3
from models.base_model import BaseModel
'''
This is the 'city' module.
city contains the class 'City', which is a sub-class of BaseModel.
'''
class City(BaseModel):
'''This is the 'City' class.
City contains two public attributes: 'state_id' and 'name'.
'''
state_id = ''
name = ''
def __init__(self, *args, **kwargs):
'''This is the initialization function.
'''
super().__init__(*args, **kwargs)
|
9ca106196ffdc6c26580d1d472cf6ee4964fcf51 | eodenyire/AirBnB_clone-7 | /tests/test_models/test_city.py | 1,284 | 3.515625 | 4 | #!/usr/bin/python3
'''
This is the 'test_city' module.
test_city uses unittest to test the 'models/city' module.
All credit for this module goes to Danton Rodriguez
(https://github.com/p0516357)
'''
import unittest
from models.city import City
import datetime
class TestCity(unittest.TestCase):
"""Test for City class
"""
def setUp(self):
"""sets up objects for testing later
"""
self.test_model1 = City()
self.test_model2 = City()
def test_basic_setup(self):
"""test for init of class attributes
"""
self.assertTrue(hasattr(self.test_model1, "state_id"))
self.assertTrue(hasattr(self.test_model1, "name"))
self.assertTrue(self.test_model1.id != self.test_model2.id)
def test_types(self):
"""testing for proper typing of city attributes
"""
self.assertTrue(type(self.test_model1.state_id) is str)
self.assertTrue(type(self.test_model1.name) is str)
def test_save(self):
"""testing whether save updates the updated_at attribute
"""
m1u = self.test_model1.updated_at
self.test_model1.save()
m1u_saved = self.test_model1.updated_at
self.assertFalse(m1u == m1u_saved)
if __name__ == '__main__':
unittest.main()
|
20f6be3633b3373d6e38a236c326f75029d536f7 | Amruthglr/PythonPrograms | /Day6/Program2.py | 491 | 4.0625 | 4 | # A Python Program to UnderStand Instance variable
class Student:
def __init__(self,name ='', age=0, marks=0):
self.firstname = name
self.age = age
self.marks = marks
sayali = Student('Sayali', 25, 90)
print(sayali.firstname)
print(sayali.age)
print(sayali.marks)
print("\n")
amruth = Student()
print(amruth.firstname)
print(amruth.age)
print(amruth.marks)
print("\n")
amruth = Student('Shiju')
print(amruth.firstname)
print(amruth.age)
print(amruth.marks) |
232896bfb010b367fdc7bbfc0c51b56d32208a1b | Amruthglr/PythonPrograms | /Day1/Program2.py | 338 | 4.4375 | 4 | age = int(input("Enter your AGE: "))
if age > 18 :
print("You are eligible to vote")
print("vote for your favourite candidate")
else:
print("You still need to wait for {} years".format(18-age))
# Another way to write
if age < 18:
print(f"You nedd still wait for {18-age} years")
else:
print("your eligible to vote")
|
a79063252fdcad3f5e7072ab714ccd1252d37b03 | Amruthglr/PythonPrograms | /Day3/Program4.py | 245 | 3.875 | 4 | #More on While Loops
Exits_available = ["East", "North", "South", "West"]
choosen_Exit = ""
while choosen_Exit not in Exits_available:
choosen_Exit = input("Enter the where do you want to exit : ")
print("arent you glad you got out out ") |
3f6087ca9c827cc0f25c0dcb75b0d41559fc6887 | Amruthglr/PythonPrograms | /Day3/Program3.py | 170 | 3.96875 | 4 | # for Loop and While Loop
for i in range(10):
print("Now value of the i is {}".format(i))
i = 0
while i < 10:
print("value of the i is {}".format(i))
i += 1 |
8f112c6bb2afdfba7f267b2196c36449b55d5524 | dpp1013/TC-track-prediction-based-on-multi-model-data | /Compare/model_RNN.py | 789 | 3.90625 | 4 | '''
RNN模型
'''
import torch
import torch.nn as nn
import numpy as np
TIME_STEP = 16 # rnn time step
INPUT_SIZE = 4 # rnn input size
LR = 1e-3 # learning rate
# LSTM
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.lstm = nn.LSTM(6, 6, 3) # 输入数据2个特征维度,6个隐藏层维度,2个LSTM串联,第二个LSTM接收第一个的计算结果
self.out = nn.Linear(6, 2) # 线性拟合,接收数据的维度为6,输出数据的维度为1
def forward(self, x):
x1, _ = self.lstm(x)
a, b, c = x1.shape
out = self.out(x1.view(-1, c))
out1 = out.view(a, b, -1)
return out1
LSTM = RNN()
print(LSTM)
test1 = torch.randn((32, 8, 6))
out1 = LSTM(test1)
print(out1.shape)
|
84402d8e4aa8d594dc246331a7677b1d766cacb4 | yatingupta10/Coding-Practice | /LeetCode/872_Leaf_Similar_Trees.py | 1,050 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
S1 = [root1]
S2 = [root2]
leaf1 = []
leaf2 = []
while S1:
node1 = S1.pop()
if node1.left:
S1.append(node1.left)
if node1.right:
S1.append(node1.right)
if not node1.left and not node1.right:
leaf1.append(node1.val)
while S2:
node2 = S2.pop()
if node2.left:
S2.append(node2.left)
if node2.right:
S2.append(node2.right)
if not node2.left and not node2.right:
leaf2.append(node2.val)
if leaf1 == leaf2:
return True
else:
return False |
f8ea97b39b452682581643011d5a73755a678cb7 | Kornvalles/Python4sem | /week_7/exercise_human.py | 424 | 3.734375 | 4 | import string
class InvalidArgumentException(Exception):
pass
class Person():
def __init__(self, name):
self.name = name
def check_name(self):
for char in self.name:
if char in string.ascii_letters and char.isupper():
return True
else:
raise InvalidArgumentException("Invalid argument!")
p = Person('Mi?kkel')
print(p.check_name())
|
98740e2a4a20e89d81f006e44d63aa333ef2a2d1 | Kornvalles/Python4sem | /week_14/regression.py | 586 | 3.5625 | 4 | import sklearn.linear_model
import pandas as pd
import numpy as np
data = pd.read_csv("/Users/mikkel/Git/Python4sem/week_14/car_sales.csv")
data.plot.scatter(x=1, y=2)
xs = data['GDP(trillion)']
ys = data['4wheeler_car_sale']
xs_reshape = np.array(xs).reshape(-1, 1)
print(xs.shape)
print(xs_reshape.shape)
model = sklearn.linear_model.LinearRegression()
model.fit(xs_reshape, ys)
print(model.coef_)
print(model.intercept_)
predicted = model.predict(xs_reshape)
GDP_10 = model.predict([[9]])
print("If GDP hits 9 trillion sales would raise to {}".format(GDP_10[0]))
print(predicted)
|
e8ce59255c8c2e48ba1536a0f59185baef9a04cf | BrandonShute/President | /president/players/base_player.py | 1,447 | 3.640625 | 4 | from abc import ABC, abstractmethod
from gameplay.president_card import PresidentCard
class BasePlayer(ABC):
def __init__(self, name: str, is_computer: bool = False):
self.name = name
self.is_computer = is_computer
self.__cards = []
@property
def cards(self) -> list:
return self.__cards
@property
def has_no_cards(self) -> bool:
return len(self.cards) == 0
@abstractmethod
def play_turn(self):
pass
def has_card(self, card: PresidentCard) -> bool:
for hand_card in self.cards:
if hand_card == card:
return True
return False
def add_cards(self, cards_to_add: list) -> None:
self.__cards.extend(cards_to_add)
def add_card(self, card_to_add: PresidentCard) -> None:
self.add_cards([card_to_add])
def remove_card(self, card_to_remove: PresidentCard) -> None:
try:
self.__cards.remove(card_to_remove)
except ValueError:
raise Exception('{} was not found in the hand.'
.format(card_to_remove.name))
def remove_cards(self, cards_to_remove: list) -> None:
for card in cards_to_remove:
self.remove_card(card)
def organize_cards(self, descending_order: bool = False) -> None:
self.__cards.sort(key=lambda card: card.president_rank,
reverse=descending_order)
|
d73f0bc73e06971c0f6af781d515cd88a40342b4 | rocciares/python-12 | /maye/1.py | 191 | 3.921875 | 4 | name=input()
if name=="alice":
print("hi,alice")
elif age < 12:
print("you ae not alice,kiddo.")
else:
print("you ar10000 朱国鹏 孟响e neither alice nor a little kid")
alice
|
655158484a1949936386badac352f2ae00d7d420 | mccarvik/poker | /app/deck_utils/deck.py | 710 | 3.546875 | 4 | import pdb
from app.deck_utils.card import Card
class Deck():
''' Class to represent a deck of cards '''
SUITS = ['s', 'h', 'c', 'd']
VALUES = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']
def __init__(self):
self.initialize()
def initialize(self):
self._cards = []
for s in self.SUITS:
for v in self.VALUES:
self._cards.append(Card(v,s))
def drawRandom(self):
pass
def removeCards(self, cards):
for c in cards:
try:
self._cards.remove(c)
except:
print("Card Already Used")
raise AssertionError
|
8f8d2783f87e8a23018d6a7eb299b782834993b8 | Euphyzr/ProjectEuler | /Python/006.py | 698 | 3.890625 | 4 | """
Sum square difference
~~~~~~~~~~~~~~~~~~~~~
The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10) ^ 2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
3025 - 385 = 2640
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
def difference(n):
sum_of_sq = (n * (n + 1) * (2*n + 1)) / 6 # = (1^2 + 2^2 + ... + n^2)
sq_of_sum = (n*(n + 1) / 2) ** 2 # = (1 + 2 + ... + n) ^ 2
return sq_of_sum - sum_of_sq
print(difference(100)) |
656fca75a084a754fff675894dd551971299d765 | Euphyzr/ProjectEuler | /Python/010.py | 122 | 3.734375 | 4 | from utils import is_prime
_sum = 0
for n in range((2 * (10 ** 6))+1):
if is_prime(n):
_sum += n
print(_sum) |
8f3eee735f0be5000162766be3de74c62effddf9 | conor36/AI-Landmark-Recognition-System | /src/generateContent.py | 649 | 3.59375 | 4 | import pandas as pd
import os
# This file is to match the building id with an id in a csv file and return a name, description and wiki link
# relevant to the building.
class BuildingData():
def getData(self,predictionID):
print(predictionID)
dataset = pd.read_csv('Workbook1.csv', encoding= 'unicode_escape')
i = 0
result = {}
for index, row in dataset.iterrows():
i = i + 1
id = row['ID']
name = row['Name']
description = row['Description']
link = row['Link']
if str(predictionID) == str(id):
result["Name"] = name
result["description"] = description
result["link"] = link
return (result)
|
c893c609523d22aa44bebbe156113ef1b7fcf729 | davidcinglis/cs-143 | /network.py | 16,916 | 3.5625 | 4 |
# This file contains all the classes and methods for the basic network architecture
from events import *
DATA_PACKET_SIZE = 1024 * 8
ACK_PACKET_SIZE = 64 * 8
TIMEOUT = 20
BIG = 10**20
class Network(object):
"""Network object for the simulation. This object contains dicts which keep track of all the nodes, links and flows in the network. It also has an event queue and an event loop method to execute the simulation."""
def __init__(self):
super(Network, self).__init__()
# Dicts of all the objects in the network, indexed by their id string
self.node_dict = dict()
self.link_dict = dict()
self.flow_dict = dict()
self.active_flows = 1
self.event_queue = EventQueue()
def add_node(self, node):
""" Method to add a node to a network. """
self.node_dict[node.node_id] = node
node.network = self
def add_link(self, link_id, node_1, node_2, buffer_size, capacity, delay):
""" Method to add a link between two nodes in the network. """
assert node_1.node_id in self.node_dict and self.node_dict[node_1.node_id] == node_1
assert node_2.node_id in self.node_dict and self.node_dict[node_2.node_id] == node_2
self.link_dict[link_id] = Link(link_id, node_1, node_2, buffer_size, capacity, delay)
self.link_dict[link_id].network = self
def add_flow(self, flow_id, source_host, destination_host, payload_size, start_time, congestion_control_algorithm):
""" Method to add a flow between two nodes in the network. """
assert source_host.node_id in self.node_dict and self.node_dict[source_host.node_id] == source_host
assert destination_host.node_id in self.node_dict and self.node_dict[destination_host.node_id] == destination_host
self.flow_dict[flow_id] = Flow(flow_id, source_host, destination_host, payload_size, start_time, congestion_control_algorithm)
source_host.flow = self.flow_dict[flow_id]
self.flow_dict[flow_id].network = self
self.flow_dict[flow_id].setup()
def event_loop(self):
""" This method starts the event loop, which executes the simulation and runs until the network is no longer sending packets. """
# Before we start, set up the routing tables of the nodes by telling them every link in the network has cost 1.
for node_id in self.node_dict:
node = self.node_dict[node_id]
node.known_link_costs = {link_id : 1 for link_id in self.link_dict}
node.update_routing_table()
# Schedule a routing update for 5 seconds into the simulation
self.event_queue.push(SendRoutingPacketsEvent(5, self))
self.active_flows = len(self.flow_dict)
# Run the event loop until the simulation ends.
while not self.event_queue.is_empty():
event = self.event_queue.pop()
# ensure correct simulation of delay
event.print_event_description()
event.handle()
class Node(object):
"""A Node Object, which is used as a superclass for Hosts and Routers."""
def __init__(self, node_id):
super(Node, self).__init__()
self.node_id = node_id
self.routing_table = {}
self.adjacent_links = []
# For updating the routing table. These represent what the node knows
# about the other links during an update.
self.known_link_costs = {}
self.routing_table_up_to_date = False
def update_routing_table(self):
""" This method uses the dict of known link costs (for the whole
network) to construct a new routing table with Dijkstra's algorithm.
"""
unvisited_nodes = {node_id for node_id in self.network.node_dict}
distance_dict = {node_id : BIG for node_id in self.network.node_dict}
previous_dict = {node_id : None for node_id in self.network.node_dict}
distance_dict[self.node_id] = 0
while unvisited_nodes:
min_dist = min(distance_dict[node] for node in unvisited_nodes)
current_vertex = [node for node in unvisited_nodes if distance_dict[node] == min_dist][0]
unvisited_nodes.remove(current_vertex)
for link in self.network.node_dict[current_vertex].adjacent_links:
adj_node = link.get_other_node(self.network.node_dict[current_vertex])
distance_through_node = distance_dict[current_vertex] + self.known_link_costs[link.link_id]
if distance_through_node < distance_dict[adj_node.node_id]:
distance_dict[adj_node.node_id] = distance_through_node
previous_dict[adj_node.node_id] = current_vertex
for node_id in self.network.node_dict:
if node_id == self.node_id:
continue
traceback_node_id = node_id
while previous_dict[traceback_node_id] != self.node_id:
traceback_node_id = previous_dict[traceback_node_id]
self.routing_table[node_id] = self.get_link_from_node_id(traceback_node_id)
def get_link_from_node_id(self, adjacent_node_id):
""" Method to get the link corresponding to an adjacent node to this node. """
for link in self.adjacent_links:
if link.get_other_node(self).node_id == adjacent_node_id:
return link
raise ValueError
def send_routing_packet(self, destination_node, time_sent):
""" This method causes a Node to send a routing table packet to a
certain destination. The routing table packet contains the current
costs of adjacent links. """
data_dict = {link.link_id : link.current_cost() for link in self.adjacent_links}
routing_packet = RoutingPacket("r" + self.node_id + "_" + destination_node.node_id, self, destination_node, time_sent, data_dict)
self.network.event_queue.push(ReceivePacketEvent(time_sent, routing_packet, self))
class Host(Node):
""" Host class, subclass of Node."""
def __init__(self, node_id):
super(Host, self).__init__(node_id)
# For a given flow, this gives the id of the next expected packet.
self.next_expected = {}
self.rec_pkts = dict()
class Router(Node):
"""Router class, subclass of Node."""
def __init__(self, node_id):
super(Router, self).__init__(node_id)
class Link(object):
"""Link object for attaching adjcent nodes."""
def __init__(self, link_id, node_1, node_2, buffer_size, capacity, delay):
super(Link, self).__init__()
self.link_id = link_id
self.node_1 = node_1
self.node_2 = node_2
self.node_1.adjacent_links.append(self)
self.node_2.adjacent_links.append(self)
# Array of all times we lost a packet
self.packets_lost_history = []
# Array of timestamps, size tuples corresponding to the available space in the buffer at that timestamp
self.buffer_occupancy_history = []
# Dict from times to amount of information sent at that time
self.link_rate_history = []
# The next time that this Link will be available to send a packet.
self.next_send_time = None
# The total size of the buffer in bits.
self.buffer_size = buffer_size
# The bandwith capacity, in bits per second, of this link.
self.capacity = capacity
# The current amount of available space of the buffer in bits.
self.available_space = buffer_size
# The transmission delay of this link.
self.delay = delay
def get_other_node(self, node):
""" A method to get the other node of this link, given one. """
if self.node_1 == node:
return self.node_2
elif self.node_2 == node:
return self.node_1
else:
raise ValueError("Node not in link")
def current_cost(self):
""" A method which computes the cost of traversing this link, computed
from the amount of data in the buffer and the capacity of the link.
Used for the cost in the shortest path routing algorithm. """
return float(self.buffer_size - self.available_space)/self.capacity
class Packet(object):
""" Packet object. """
def __init__(self, packet_id, source, destination):
super(Packet, self).__init__()
self.source = source
self.destination = destination
self.packet_id = packet_id
class DataPacket(Packet):
""" Subclass of Packet for packets which represent host-to-host payload
comunication."""
def __init__(self, packet_id, source, destination):
super(DataPacket, self).__init__(packet_id, source, destination)
self.size = DATA_PACKET_SIZE # All data packets have 1024 bytes
class AcknowledgementPacket(Packet):
""" Subclass of Packet for acknowledgement packets."""
def __init__(self, packet_id, source, destination, ACK):
super(AcknowledgementPacket, self).__init__(packet_id, source, destination)
self.size = ACK_PACKET_SIZE # All acknowledgement packets have 64 bytes.
self.ACK = ACK
class RoutingPacket(Packet):
""" Subclass of packet for inter-router communication of link costs for
routing table updates."""
def __init__(self, packet_id, source, destination, time_sent, data_dict):
super(RoutingPacket, self).__init__(packet_id, source, destination)
self.size = DATA_PACKET_SIZE
self.time_sent = time_sent
self.data_dict = data_dict
class Flow(object):
""" Class to represent data flows."""
def __init__(self, flow_id, source_host, destination_host, payload_size, start_time, congestion_control_algorithm):
super(Flow, self).__init__()
self.flow_id = flow_id
self.source_host = source_host
self.destination_host = destination_host
# Map from received packet ids to their round trip times
self.round_trip_time_history = {}
self.payload_size = payload_size
self.start_time = start_time
# Packets that are in transit, never delete from this, used to calculate round trip time
# Map from psuhed packet ids to time they were pushed
self.pushed_packets = {}
# packets in transit, map from packet_ids to the times at which they were sent, used in
# congestion control
self.unacknowledged_packets = {}
# Packets that need to be sent to source host
self.unpushed = []
# an array of timestamp, bytes_sent tuples, used to plot
self.flow_rate_history = []
# initialize window size to 20
self.WINDOW_SIZE = 20
# initialize threshold to 50, used in TCP Reno
self.THRESHOLD = 500
# array hold ids of last 3 acknowledgments
self.prev_ack = [-1, -1, -1]
# initialize minimum round trip time to a large value
self.baseRTT = 1000
# array contains changing values of window size, used to plot
self.window_size_history = []
# type of congestion control algorithm
self.alg_type = congestion_control_algorithm
# number of packets to be sent and received
self.num_packets = self.payload_size / DATA_PACKET_SIZE
# initialize gamma and alpha for TCP Fast
self.gamma = 0.5
self.alpha = 15
# This method updates the window size accordingly if a successful ack occurrs in
# the slow start phase.
def slow_start(self):
self.WINDOW_SIZE += 1
return self.WINDOW_SIZE
# Tis method updates the window size accordingly if a successful ack occurrs in
# the congestion avoidance phase
def cong_avoid(self):
self.WINDOW_SIZE += 1 / self.WINDOW_SIZE
return self.WINDOW_SIZE
# this method implements the TCP Reno congestion control algorithm
def reno(self, packet, current_time):
# delete any packet with pcket id less than current one from
# unacknowledged packets dictionary since we assume
# all packets with id less than current have also been
# acknowledged
temp_unack = self.unacknowledged_packets.keys()
for p in temp_unack:
if int(p[3:]) < int(packet.ACK[3:]):
del self.unacknowledged_packets[p]
# shift last two elements to be first two
for i in range(2):
self.prev_ack[i] = self.prev_ack[i + 1]
# replace last element with new ack
self.prev_ack[2] = packet.ACK
# if triple ack occurs
if self.prev_ack[0] == self.prev_ack[1] and self.prev_ack[1] == self.prev_ack[2]:
# cut threshold to half of current window size
self.THRESHOLD = self.WINDOW_SIZE / 2
# halve window size
self.WINDOW_SIZE = max(self.WINDOW_SIZE / 2.0, 1.0)
self.window_size_history.append((current_time, self.WINDOW_SIZE))
current_time += .01
# resend lost packet
if int(packet.ACK[3:]) < self.num_packets and int(packet.ACK[3:]) not in self.unpushed:
heapq.heappush(self.unpushed, int(packet.ACK[3:]))
# if successful ack occurrs, update window size accordingly
else:
if self.WINDOW_SIZE <= self.THRESHOLD:
self.window_size_history.append((current_time, self.slow_start()))
else:
self.window_size_history.append((current_time, self.cong_avoid()))
#self.WINDOW_SIZE = self.WINDOW_SIZE + 1.0 / self.WINDOW_SIZE
self.send(current_time)
# this method implements the TCP Reno congestion control algorithm
def fast(self, packet, current_time):
# delete any packet with pcket id less than current one from
# unacknowledged packets dictionary since we assume
# all packets with id less than current have also been
# acknowledged
temp_unack = self.unacknowledged_packets.keys()
for p in temp_unack:
if int(p[3:]) < int(packet.ACK[3:]):
del self.unacknowledged_packets[p]
# shift last two elements to be first two
for i in range(2):
self.prev_ack[i] = self.prev_ack[i + 1]
# replace last element with new ack
self.prev_ack[2] = packet.ACK
# if duplicate ack occurs
if self.prev_ack[1] == self.prev_ack[2]:
# halve window size
self.WINDOW_SIZE = max(self.WINDOW_SIZE / 2.0, 1.0)
self.window_size_history.append((current_time, self.WINDOW_SIZE))
current_time += .01
# resend lost packet
if int(packet.ACK[3:]) < self.num_packets and int(packet.ACK[3:]) not in self.unpushed:
heapq.heappush(self.unpushed, int(packet.ACK[3:]))
# if a successful ack occurs
elif int(packet.ACK[3:]) < self.num_packets:
curr_rtt = self.round_trip_time_history[packet.packet_id]
# update minimum round trip time
self.baseRTT = min(self.baseRTT, curr_rtt)
w = self.WINDOW_SIZE
# update window size accordingly
self.WINDOW_SIZE = min(2 * w, (1 - self.gamma) * w + self.gamma * ((self.baseRTT / curr_rtt) * w + self.alpha))
self.window_size_history.append((current_time, self.WINDOW_SIZE))
self.send(current_time, False)
# This method sends packets
def send(self, execution_time, timeout = True):
self.unpushed.sort(reverse = True)
# while there the number of packets in transit does not reach the window size and
# there are packets to send, sontinue to send packets
while (len(self.unacknowledged_packets) < self.WINDOW_SIZE) and self.unpushed:
execution_time += .00000001
packet_num = self.unpushed.pop()
packet_id = str(self.flow_id) + "_" + str(packet_num)
self.unacknowledged_packets[packet_id] = execution_time
self.pushed_packets[packet_id] = execution_time
packet = DataPacket(packet_id, self.source_host, self.destination_host)
self.flow_rate_history.append((execution_time, DATA_PACKET_SIZE))
# send packets and timeout event (if tcp reno)
self.network.event_queue.push(ReceivePacketEvent(execution_time, packet, self.source_host))
# if tcp fast, push a timeout event
if timeout:
self.network.event_queue.push(TimeoutEvent(execution_time + TIMEOUT, packet, self))
def setup(self):
global TIMEOUT
for packet in range(self.num_packets):
packet_id = packet
heapq.heappush(self.unpushed, packet_id)
if self.alg_type == "reno":
self.send(self.start_time)
# dont add timeout events in tcp fast
else:
self.send(self.start_time, False)
|
35752984c3f813399abe474dcee249f17b3dbb6c | mafdezmoreno/HackerRank_Callenges | /Practice/ProblemSolving/SparseArrays.py | 734 | 3.625 | 4 | #https://www.hackerrank.com/challenges/sparse-arrays/problem
import math
import os
import random
import re
import sys
# Complete the matchingStrings function below.
def matchingStrings(strings, queries):
recuento = []
#print(strings)
#print(queries)
for i in range(len(queries)):
#recuento.append(strings.count(queries[i]))
print(strings.count(queries[i])
#print(recuento)
if __name__ == '__main__':
strings = ['abcde', 'sdaklfj', 'asdjf', 'na', 'basdn', 'sdaklfj', 'asdjf', 'na', 'asdjf', 'na', 'basdn', 'sdaklfj', 'asdjf']
queries = ['abcde', 'sdaklfj', 'asdjf', 'na', 'basdn']
matchingStrings(strings, queries)
# Sample output:
'''
1
3
4
3
2
''' |
b4131f154cbc2d62220d55c8b177e934d59a7cfa | mafdezmoreno/HackerRank_Callenges | /Practice/ProblemSolving/Node_at_head.py | 1,318 | 3.953125 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-list/problem?h_r=next-challenge&h_v=zen&isFullScreen=true
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def print_singly_linked_list(node):#, sep, fptr):
while node:
#fptr.write(str(node.data))
print(node.data)
node = node.next
#if node:
# fptr.write(sep)
def insertNodeAtHead(llist, data):
if llist == None:
llist = SinglyLinkedListNode(data)
return llist
temp = llist
llist = SinglyLinkedListNode(data)
llist.next = temp
return llist
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
#llist_count = int(input())
llist_count = 5
input = [383, 484, 392, 975, 321]
llist = SinglyLinkedList()
for i in range(llist_count):
#llist_item = int(input())
llist_item = input[i]
llist_head = insertNodeAtHead(llist.head, llist_item)
llist.head = llist_head
print_singly_linked_list(llist.head)
#print_singly_linked_list(llist.head, '\n', fptr)
#fptr.write('\n')
#fptr.close() |
40f2886dd9a9df5af1a7b579439924a38d006358 | Mateuus/A3UndeadBRLife | /BEC/Plugin Examples/Function_Extensions/__init__.py | 5,325 | 3.921875 | 4 |
class Function_Extensions(object):
'''A Example Class to Extend some functions in Bec'''
def __init__(self, instance):
self.bec = instance
self.mytext = "This is just an example text string!"
########################################################
## Orginale functions we want to extend. Make a copy. ##
# the function that triggers when a player connects.
self.org_func_connected = self.bec._be_connected
# the function that triggers when a player disconnects.
self.org_func_disconnected = self.bec._be_disconnected
# the function that triggers when a player gets unverified.
self.org_func_unverified = self.bec._be_unverified
# the function that triggers when a player gets verified.
self.org_func_verified = self.bec._be_verified
# the function that triggers when a player chats.
self.org_func_chat = self.bec._be_chat
################################
## Monkey patch the functions ##
self.bec._be_connected = self.connected
self.bec._be_disconnected = self.disconnected
self.bec._be_unverified = self.unverified
self.bec._be_verified = self.verified
self.bec._be_chat = self.chat
def Be_PlayerConnected(func):
'''
This will extend the connected function.
Add your extra code into extended_data -> finally.
Arg 0 can be considered as self.
Arg 1 will be a regex obj
'''
def extended_data(*args, **kwargs):
try:
return func(*args, **kwargs)
finally:
player_name = args[1].groups()[1]
player_ipp = args[1].groups()[2].split(":")
player_ip = player_ipp[0]
player_port = player_ipp[1]
print "name:",player_name," Connected with Ip:",player_ip," Using Port:",player_port
return extended_data
def Be_PlayerDisconnected(func):
'''
This will extend the disconnected function
Add your extra code into extended_data -> finally.
arg 0 can be considered as self.
arg 1 will be a regex obj
'''
def extended_data(*args, **kwargs):
try:
return func(*args, **kwargs)
finally:
player_name = args[1].groups()[0]
print player_name,"Has Disconnected from the Server"
return extended_data
def Be_PlayerUnverified(func):
'''
This will extend the unverified function
Add your extra code into extended_data -> finally.
Arg 0 can be considered as self.
Arg 1 will be a regex obj
'''
def extended_data(*args, **kwargs):
try:
return func(*args, **kwargs)
finally:
udata = args[1].groups()
beid = udata[0]
nick = udata[1]
guid = udata[2]
print "guid "+guid+" of player "+nick+" has been unverified"
return extended_data
def Be_PlayerVerified(func):
'''
This will extend the verified function
Add your extra code into extended_data -> finally.
Arg 0 can be considered as self.
Arg 1 will be a regex obj
'''
def extended_data(*args, **kwargs):
try:
return func(*args, **kwargs)
finally:
vdata = args[1].groups()
guid = vdata[0]
beid = vdata[1]
nick = vdata[2]
print "guid "+guid+" of player "+nick+" has been verified"
return extended_data
def Be_PlayerChat(func):
'''
This will extend the connected function
Add your extra code into extended_data -> finally.
Arg 0 can be considered as self.
Arg 1 will be a regex obj
'''
def extended_data(*args, **kwargs):
try:
return func(*args, **kwargs)
finally:
self = args[0]
cdata = args[1].groups()
chat_channel = cdata[0]
player_name = cdata[1]
chat_text = cdata[2]
# UNSAFE
if player_name == "nux" and chat_text.lower() == "danger":
print self.mytext
# SAFEST
if chat_text.lower() == "danger":
# We dont know the guid, so find the guid assosiated with the player name
for guid in self.bec._Bec_playersconnected.keys():
try:
if self.bec._Bec_playersconnected[guid][1] == player_name:
print "Got the guid:",guid,"of player:",player_name
print "You can now make events based on input from this player."
break
except:
print "Some error occured trying to find the player guid"
else:
print "No players are yet verified.. can not get the player guid."
else:
print "type danger on the chat"
return extended_data
# Use decorators to extend the functions
@Be_PlayerConnected
def connected(self,data):
'''This is a moneky patched function which uses a decorator to extends the orginale function'''
self.org_func_connected(data)
@Be_PlayerDisconnected
def disconnected(self,data):
'''This is a moneky patched function which uses a decorator to extends the orginale function'''
self.org_func_disconnected(data)
@Be_PlayerUnverified
def unverified(self,data):
'''This is a moneky patched function which uses a decorator to extends the orginale function'''
self.org_func_unverified(data)
@Be_PlayerVerified
def verified(self,data):
'''This is a moneky patched function which uses a decorator to extends the orginale function'''
self.org_func_verified(data)
@Be_PlayerChat
def chat(self,data):
'''This is a moneky patched function which uses a decorator to extends the orginale function'''
self.org_func_chat(data)
def start(i):
Function_Extensions(i)
|
42b77c069625890a9c38ba595d2065b32b1fd09b | jgrimes91/cp1404practicals | /prac_01/loops.py | 279 | 4.0625 | 4 | for i in range (1, 21, 2):
print(i, end=" ")
print()
for i in range (0, 100, 10):
print(i, end=" ")
print()
for i in range (20, 0, -1):
print(i, end=" ")
print()
stars = int(input("Enter number of stars: "))
for i in range (stars):
n = i + 1
print("*" * n) |
ccc04fabc35863c31fdb6f683f910a768d245d82 | scottbing/SB_5410_Hwk131 | /Hwk131/iris_classification/venv/iris_classification.py | 6,061 | 3.625 | 4 | from sklearn.datasets import load_iris
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
from statistics import mean
import matplotlib.pyplot as plt
import numpy as np
from Perceptron import *
import random
def load_data():
iris = load_iris()
# convert numpyarr to list get first index of 2
cutoff = list(iris.target).index(2)
# throw away data and labels after cutoff
iris.data = iris.data[:cutoff]
iris.target = iris.target[:cutoff]
return iris
# end def load_data():
def sum_row(row):
# assumes row of length 4 is constant
# calculate weighted sum
wsum = row[0] * 0.05 + row[1] * 0.08 + row[2] * 0.75 + row[3] * 1.9
# return sum(row)
return wsum
# end def sum_row(row):
def average(data):
size = data.shape[0]
summ = 0
for row in range(size):
summ += sum_row(data[row])
return summ / size
# end def average(data):
def test(data, ans, tol):
sum_res = 0
for row in data:
summ = sum_row(row)
# result = summ + tol > ans and summ - tol < ans
result = int(summ + tol > ans > summ - tol)
sum_res += result
# prints accurate percentage. If showuld be false then 0.0 will be 100%
print(sum_res / len(data))
# end def test(data, ans,tol):
def main_naive():
iris = load_data()
# find where types change
versic_idx = list(iris.target).index(1)
# separate all setosa and versic types
sertosa = iris.data[:versic_idx]
versic = iris.data[versic_idx:]
# first 80 percent to train on
sertosa_train = sertosa[:int(len(sertosa) * .8)]
# remaining 20% to test with
sertosa_test = sertosa[int(len(sertosa) * .8):]
# first 80 percent to train on
versic_train = versic[:int(len(sertosa) * .8)]
# remaining 20% to test with
versic_test = versic[int(len(sertosa) * .8):]
print("Should be trues")
test(sertosa_test, average(sertosa_train), 1)
print("Should be falses")
test(versic_test, average(sertosa_train), 1)
print("Should be trues")
test(versic_test, average(versic_train), 1)
print("Should be falses")
test(sertosa_test, average(versic_train), 1)
print("s ave: ", average(sertosa_train))
print("v ave: ", average(versic_train))
# end def main_naive():
def main_bkup():
iris = load_data()
train_data = iris.data[:int(len(iris.data) * .8)]
test_data = iris.data[int(len(iris.data) * .8):]
train_label = iris.target[:int(len(iris.data) * .8)]
test_label = iris.target[int(len(iris.data) * .8):]
classifier = Perceptron(learning_rate=0.1)
classifier.fit(train_data, train_label, 20)
print("Computed weights are: ", classifier._w)
for i in range(len(test_label)):
print(classifier.predict(test_data[i]), test_label[i])
# end def main_bkup():
def scatter_plot(x, y, col, fnames):
plt.scatter(x,y,c=col)
plt.title("Iris Dataset Scatterplot")
plt.xlabel(fnames[0])
plt.ylabel(fnames[1])
#plt.show()
#end def scatter_plot(x, y, col, fnames):
def graph_decision(ymin, ymax, x, y, weights, bias):
w = (bias, weights[0], weights[1])
xx = np.linspace(ymin, ymax)
slope = -(w[0]/w[2])/(w[0]/w[1])
intercept = -w[0]/w[2]
yy = (slope*xx) + intercept
plt.scatter(x, y)
plt.plot(xx, yy, 'k-')
plt.show()
def best_fit_slope_and_intercept(xs, ys, col, fnames):
# m = (((mean(xs) * mean(ys)) - mean(np.multiply(xs, ys))) /
# ((mean(xs) * mean(xs)) - mean(np.multiply(xs, xs))))
m = (((mean(xs) * mean(ys)) + mean(np.multiply(xs, ys))) /
((mean(xs) * mean(xs)) + mean(np.multiply(xs, xs))))
# m = (((mean(xs) * mean(ys)) - mean(np.multiply(xs, ys))) /
# ((mean(xs) * mean(xs)) - mean(np.multiply(xs, xs))))
b = mean(ys) - m * mean(xs)
print(m, b)
regression_line = [(m*x)+b for x in xs]
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
#plt.scatter(xs,ys)
plt.scatter(xs, ys, c=col)
plt.title("Iris Dataset Scatterplot")
plt.xlabel(fnames[0])
plt.ylabel(fnames[1])
plt.plot(xs, regression_line)
plt.show()
def main():
iris = load_data()
versic_idx = list(iris.target).index(1)
sertosa = iris.data[:versic_idx]
versic = iris.data[versic_idx:]
sertosa_label = iris.target[:versic_idx]
versic_label = iris.target[versic_idx:]
sertosa_train = sertosa[:int(len(sertosa) * .8)]
sertosa_test = sertosa[int(len(sertosa) * .8):]
versic_train = versic[:int(len(versic) * .8)]
versic_test = versic[int(len(versic) * .8):]
sertosa_label_train = sertosa_label[:int(len(sertosa) * .8)]
sertosa_label_test = sertosa_label[int(len(sertosa) * .8):]
versic_label_train = versic_label[:int(len(versic) * .8)]
versic_label_test = versic_label[int(len(versic) * .8):]
train_data = np.concatenate((sertosa_train, versic_train))
test_data = np.concatenate((sertosa_test, versic_test))
train_label = np.concatenate((sertosa_label_train, versic_label_train))
test_label = np.concatenate((sertosa_label_test, versic_label_test))
#plotting only 2 dimesnsions of the data, the first two vals
# scatter_plot([val[0] for val in train_data], [val[1] for val in train_data],
# train_label, iris.feature_names)
classifier = Perceptron(learning_rate=0.1)
classifier.fit(train_data, train_label, 30)
print("Computed weights are: ", classifier._w)
# graph_decision(min([val[0] for val in train_data]), max([val[0] for val in train_data]),
# [val[0] for val in train_data], [val[0] for val in train_data],
# classifier._w, classifier._b)
best_fit_slope_and_intercept([val[0] for val in train_data], [val[1] for val in train_data],
train_label, iris.feature_names)
for i in range(len(test_label)):
print(max(0, classifier.predict(test_data[i])), test_label[i])
# end def main():
if __name__ == "__main__":
main()
|
98eff7c1eca1037699371f251ca50565da2a2739 | helpmoeny/pythoncode | /Python_labs/lab06/lab06_stub.py | 467 | 3.9375 | 4 |
def make_new_row(old_row):
"""Requires:
-- list old_row that begins and ends with a 1 and has zero or more
integers in between (has to have at least [1,1])
Returns:
-- list beginning and ending with a 1 and each interior (non 1)
integer is the sum of the corresponding old_row elements
For example if old_row = [ 1,4,6,4,1], then new_row = [1,5,10,10,5,1],
i.e. 5=1+4, 10=4+6, 10=6+4, 5=4+1 """
|
364bc17b6f406fb702e36dc19bb16411657def85 | helpmoeny/pythoncode | /Python_projects/project10/currency.py | 4,115 | 3.6875 | 4 | import urllib.request
class Currency( object ):
def __init__(self,amount=0,currencycode=""):
"""Initialize an object of type Currency"""
self.__amount = 0
self.__currencycode = ""
#print(amount) #print the current amount in object
#print(currencycode) #display
if isinstance(amount,int) or isinstance(amount,float) and isinstance(currencycode,str):
self.__amount=amount
self.__currencycode=currencycode
else:
print('error input type')
amount = self.__amount
currencycode = self.__currencycode
def __repr__( self ):
"""
Return a string (the representation of a Currency).
"""
amount=self.__amount
currencycode=self.__currencycode
return("{:.2f}, {}".format(amount,currencycode))
def __str__( self ):
"""
Return a string (the representation of a Currency).
"""
amount=self.__amount
currencycode=self.__currencycode
return("Amount= {:.2f}, Currency: {}".format(amount,currencycode))
def convert_to(self,newcurrencycode):
amount=self.__amount
currencycode=self.__currencycode
if newcurrencycode=='USD' or newcurrencycode=='EUR' or newcurrencycode=='SEK' or newcurrencycode=='CAD' or newcurrencycode=='CNY' or newcurrencycode=='GDP':
web_obj = urllib.request.urlopen("https://www.google.com/finance/converter?a="+str(amount)+"&from="+currencycode+"&to="+newcurrencycode+"")
results_str = str(web_obj.read())
web_obj.close()
line_lst=results_str.split('currency_converter_result')
currency_str= ''.join(c for c in line_lst[1] if c not in '(){}<>&abcdefghijklmnopqrstuvwxyz/\=#;:"')
#print(x) #whole document, after split(list)
#print(x[1]) #line i want from list
#print(currency_str) #broken down line
currency_lst=currency_str.split(" ") #0,1 4,5
#print(currency_lst) #broken down list of broken down line
new_amount=float(currency_lst[4])
new_currency=currency_lst[5]
old_amount=currency_lst[0]
old_currency=currency_lst[1]
return Currency(new_amount,new_currency)
else:
print("Blank/Incorrect Currency type")
def __add__(self, other):
if isinstance(other,Currency):
#add the two currencies
other_currencyconverted = other.convert_to(self.__currencycode)
other_amount=self.__amount+other_currencyconverted.__amount
return Currency(other_amount,self.__currencycode)
if isinstance(other,int) or isinstance(other,float):
new_amount=self.__amount+other
return Currency(new_amount,self.__currencycode)
def __radd__(self, other):
# operands reversed as part of invocation
return Currency(other + self.__amount,self.__currencycode)
def __sub__(self, other):
if isinstance(other,Currency):
other_currencyconverted = other.convert_to(self.__currencycode)
other_amount=self.__amount-other_currencyconverted.__amount
return Currency(other_amount,self.__currencycode)
if isinstance(other,int) or isinstance(other,float):
new_amount=self.__amount-other
return Currency(new_amount,self.__currencycode)
def __rsub__(self, other):
# operands reversed as part of invocation
return Currency(other-self.__amount,self.__currencycode)
def __gt__(self, other):
# checks to see if the other object is greater than the current self currency amount
if isinstance(other,Currency):
other_currencyconverted = other.convert_to(self.__currencycode)
other_amount=other_currencyconverted.__amount
if self.__amount > other_amount:
return True
else:
return False
else:
print("object is not of type Currency")
|
75eea7ac650c7425843c23b8b107d987b2ca4e5e | helpmoeny/pythoncode | /Python_projects/project08/freecellStart.py | 6,320 | 3.8125 | 4 | import cards
def setup():
"""
paramaters: None (deck can be created within this function)
returns:
- a foundation (list of 4 empty lists)
- cell (list of 4 empty lists)
- a tableau (a list of 8 lists, the dealt cards)
"""
foundation = None # temporary value that needs to be replaced
cell = None # temporary value that needs to be replaced
tableau = None # temporary value that needs to be replaced
return foundation,tableau,cell
def move_to_foundation(tableau,foundation,t_col,f_col):
'''
parameters: a tableau, a foundation, column of tableau, column of foundation
returns: Boolean (True if the move is valid, False otherwise)
moves a card at the end of a column of tableau to a column of foundation
This function can also be used to move a card from cell to foundation
'''
pass
def move_to_cell(tableau,cell,t_col,c_col):
'''
parameters: a tableau, a cell, column of tableau, column of cell
returns: Boolean (True if the move is valid, False otherwise)
moves a card at the end of a column of tableau to a cell
'''
pass
def move_to_tableau(tableau,foundation,t_col,f_col):
'''
parameters: a tableau, a cell, column of tableau, a cell
returns: Boolean (True if the move is valid, False otherwise)
moves a card in the cell to a column of tableau
remember to check validity of move
'''
pass
def is_winner(foundation):
'''
parameters: a foundation
return: Boolean
'''
pass
def move_in_tableau(tableau,t_col_source,t_col_dest):
'''
parameters: a tableau, the source tableau column and the destination tableau column
returns: Boolean
move card from one tableau column to another
remember to check validity of move
'''
pass
def print_game(foundation, tableau,cell):
"""
parameters: a tableau, a foundation and a cell
returns: Nothing
prints the game, i.e, print all the info user can see.
Includes:
a) print tableau
b) print foundation ( can print the top card only)
c) print cells
"""
print()
print(" Cells: Foundation:")
# print cell and foundation labels in one line
for i in range(4):
print('{:8d}'.format(i+1), end = '')
print(' ', end = '')
for i in range(4):
print('{:8d}'.format(i+1), end = '')
print() # carriage return at the end of the line
# print cell and foundation cards in one line; foundation is only top card
for c in cell:
# print if there is a card there; if not, exception prints spaces.
try:
print('{:8s}'.format(c[0]), end = '')
except IndexError:
print('{:8s}'.format(''), end = '')
print(' ', end = '')
for stack in foundation:
# print if there is a card there; if not, exception prints spaces.
try:
print('{:8s}'.format(stack[-1]), end = '')
except IndexError:
print('{:8s}'.format(''), end = '')
print() # carriage return at the end of the line
print('----------')
print("Tableau")
for i in range(len(tableau)): # print tableau headers
print('{:8d}'.format(i + 1), end = '')
print() # carriage return at the end of the line
# Find the length of the longest stack
max_length = max([len(stack) for stack in tableau])
# print tableau stacks row by row
for i in range(max_length): # for each row
print(' '*7, end = '') # indent each row
for stack in tableau:
# print if there is a card there; if not, exception prints spaces.
try:
print('{:8s}'.format(stack[i]), end = '')
except IndexError:
print('{:8s}'.format(''), end = '')
print() # carriage return at the end of the line
print('----------')
def print_rules():
'''
parameters: none
returns: nothing
prints the rules
'''
print("Rules of FreeCell")
print("Goal")
print("\tMove all the cards to the Foundations")
print("Foundation")
print("\tBuilt up by rank and by suit from Ace to King")
print("Tableau")
print("\tBuilt down by rank and by alternating color")
print("\tThe bottom card of any column may be moved")
print("\tAn empty spot may be filled with any card ")
print("Cell")
print("\tCan only contain 1 card")
print("\tThe card may be moved")
def show_help():
'''
parameters: none
returns: nothing
prints the supported commands
'''
print("Responses are: ")
print("\t t2f #T #F - move from Tableau to Foundation")
print("\t t2t #T1 #T2 - move card from one Tableau column to another")
print("\t t2c #T #C - move from Tableau to Cell")
print("\t c2t #C #T - move from Cell to Tableau")
print("\t c2f #C #F - move from Cell to Foundation")
print("\t 'h' for help")
print("\t 'q' to quit")
def play():
'''
Main program. Does error checking on the user input.
'''
print_rules()
foundation, tableau, cell = setup()
show_help()
while True:
# Uncomment this next line. It is commented out because setup doesn't do anything so printing doesn't work.
print_game(foundation, tableau, cell)
response = input("Command (type 'h' for help): ")
response = response.strip()
response_list = response.split()
if len(response_list) > 0:
r = response_list[0]
if r == 't2f':
pass # you implement
elif r == 't2t':
pass # you implement
elif r == 't2c':
pass # you implement
elif r == 'c2t':
pass # you implement
elif r == 'c2f':
pass # you implement
elif r == 'q':
break
elif r == 'h':
show_help()
else:
print('Unknown command:',r)
else:
print("Unknown Command:",response)
print('Thanks for playing')
play()
|
51272948d3a64762b7abbb98bff568e9e86875ff | helpmoeny/pythoncode | /Python_projects/project11/proj11old.py | 5,117 | 4.03125 | 4 | import random
import turtle
import time
from random import choice
from random import randrange
class Fishing(object):
def Fish():
#creating multiple types of object fish types and returning one of them
Fish = ['Whale Shark','Jack','Blacktip Shark','Tarpon','Roosterfish','Yellowfin Tuna','Peacock Bass','Cubera Snapper','Barracuda','Snapper','Wahoo','Blue Marlin','Black Marlin','Striped Marlin','Sailfish','Dorado','Amberjack','Bluefin','Bonito','Corvina','Red Stripe Rockfish','Sierra Mackered','Grouper','Hammerhead Shark','Pompano']
return choice(Fish)
class Carpet(object):
def gotoandprint(x, y):
turtle.goto(x, y)
#time.sleep(10)
print()
print("Set hook:")
print(turtle.xcor(), turtle.ycor())
x=turtle.xcor()
y=turtle.ycor()
coordinate=[x,y]
return coordinate
def click_position(turtle):
turtle.onscreenclick(Carpet.gotoandprint)
x=turtle.xcor()
y=turtle.ycor()
return x,y
def Draw_square(x,y,length_str):
t=turtle
t.title("Carpet fishing") #displays given text in turtle window(bar)
#t.shape('Fish')
t.penup()
t.goto(x,y)
t.pensize()
t.setheading(0)
#0:east,90:north,180:west,270:south
t.pendown()
t.speed(10)
length=int(length_str)
i=0
for i in range(4):
t.forward(length)
t.left(90)
i+=1
t.penup()
#t.ht()#hide turtle
def Draw_carpet():
while True:
print("Type 'Q' or 'q' if you want to quit...")
#try:
squares=input("How wide would you like each grid square? (integer)")
if squares=='Q' or squares== 'q':
break
width=input("How many grid squares wide is your carpet? (integer)")
if width=='Q' or width== 'q':
break
length=input("How many grid squares long is your carpet? (integer)")
if length=='Q' or length== 'q':
break
squares_int=int(squares)
width_int=int(width)
length_int=int(length)
if width_int<0 or length_int<0 or squares_int<0:
print("No negative values...")
elif width_int==0 or length_int==0 or squares_int==0:
print("Can't have a carpet of no width or no length or 0 width of a grid square")
else:
x=0#origin x value
y=0
lst_of_gridsquares=[]
row_gridlst=[]
k=0
L=4
for i in range(length_int):
for j in range(width_int):
Carpet.Draw_square(x,y,squares_int)
row_gridlst.append(x)
row_gridlst.append(y)
row_gridlst.append(x+squares_int)
row_gridlst.append(y+squares_int)
x+=squares_int#x change
turtle.goto(x,y)
for h in range(length_int):
lst_of_gridsquares.append(row_gridlst[k:L])#appending a single squares x,y values from row_gridlst to lst_of_gridsquares
k+=4
L+=4
#print(row_gridlst[k:L])#That square in the row_gridlst
#print(lst_of_gridsquares)
row_gridlst=[]#setting that row's row_gridlst back to empty, doesn't need to be here to work correctly
k=0#setting the row_gridlst grab points for the square back to starting x value, only to be used when the row_gridlst is set back to empty, doesn't need to be here to work correctly
L=4#setting the row_gridlst grab points for the square back to starting x value, only to be used when the row_gridlst is set back to empty, doesn't need to be here to work correctly
y+=squares_int#y change
x=0#origin x value
turtle.goto(x,y)
turtle.penup()
print("Done Drawing Carpet...")
break
return lst_of_gridsquares
#except:
#print("An error occured, please try again...")
#pass
def main():
grid_lst=Carpet.Draw_carpet()
#print(grid_lst)#displays all the coordinate values that define the regions of grid squares
fish=Fishing.Fish()
#print(fish)#fish it chose
#print(choice(fish))#shows how it picked what type fish
random_index = randrange(0,len(grid_lst))#a.k.a fish square location, randomized
cor_click=Carpet.click_position(turtle)
fo=input("Click on the screen to set the hook for fishing, then enter ok")
print(cor_click)
x=grid_lst[random_index][0]
y=grid_lst[random_index][1]
b=grid_lst[random_index][2]
a=grid_lst[random_index][3]
print(x)
print(y)
print(b)
print(a)
main()
|
0791a754b6620486dd07026672d3e27dd533da7f | helpmoeny/pythoncode | /Python_labs/lab09/warmup1.py | 2,104 | 4.34375 | 4 | ##
## Demonstrate some of the operations of the Deck and Card classes
##
import cards
# Seed the random number generator to a specific value so every execution
# of the program uses the same sequence of random numbers (for testing).
import random
random.seed( 25 )
# Create a deck of cards
my_deck = cards.Deck()
# Display the deck (unformatted)
print( "===== initial deck =====" )
print( my_deck )
print()
# Display the deck in 13 columns
print( "===== initial deck =====" )
my_deck.pretty_print( column_max=13 )
# Shuffle the deck, then display it in 13 columns
my_deck.shuffle()
print( "===== shuffled deck =====" )
my_deck.pretty_print( column_max=13 )
# Deal first card from the deck and display it (and info about the deck)
card1 = my_deck.deal()
print( "First card dealt from the deck:", card1 )
print()
print( "Card suit:", card1.get_suit() )
print( "Card rank:", card1.get_rank() )
print( "Card value:", card1.get_value() )
print()
print( "Deck empty?", my_deck.is_empty() )
print( "Number of cards left in deck:", my_deck.cards_count() )
print()
# Deal second card from the deck and display it (and info about the deck)
card2 = my_deck.deal()
print( "Second card dealt from the deck:", card2 )
print()
print( "Card suit:", card2.get_suit() )
print( "Card rank:", card2.get_rank() )
print( "Card value:", card2.get_value() )
print()
print( "Deck empty?", my_deck.is_empty() )
print( "Number of cards left in deck:", my_deck.cards_count() )
print()
# Compare the two cards
if card1.equal_suit( card2 ):
print( card1, "same suit as", card2 )
else:
print( card1, "and", card2, "are from different suits" )
if card1.equal_rank( card2 ):
print( card1, "and", card2, "of equal rank" )
elif card1.get_rank() > card2.get_rank():
print( card1, "of higher rank than", card2 )
else:
print( card2, "of higher rank than", card1 )
if card1.equal_value( card2 ):
print( card1, "and", card2, "of equal value" )
elif card1.get_value() > card2.get_value():
print( card1, "of higher value than", card2 )
else:
print( card2, "of higher value than", card1 )
|
19e67bca21d2cf81f91d6abb344154755d3b9ec3 | helpmoeny/pythoncode | /other/binaryencoder.py | 111 | 4.09375 | 4 | temp=input("Enter text: ")
newbinvalue=""
for ch in temp:
newbinvalue+=bin(ord(ch))[2:]
print(newbinvalue)
|
309cca0dbdbadfb32981e1b5cd1585c0f48c9272 | allandieguez/project_euler | /problems/problem_12/problem_solution.py | 967 | 3.734375 | 4 | from problems.problem_12.problem_statement import NUMBER_OF_DIVISORS
from problems.utils import factorize
divisor_map = {}
def count_divisors(number):
if number in divisor_map.keys():
return divisor_map[number]
_, counter = factorize(number)
if counter:
div_count = counter[0] + 1
for c in counter[1:]:
div_count *= c+1
else:
div_count = 1
divisor_map[number] = div_count
return div_count
def triangular_number(nth):
return nth * (nth + 1) / 2
def find_highly_divisible_triangular_number(num_factors):
nf = 1
max_nf = 1
n = 0
while nf < num_factors:
n += 1
nf = count_divisors(triangular_number(n))
if max_nf < nf:
max_nf = nf
print n, triangular_number(n), nf
return triangular_number(n), nf
def main():
return find_highly_divisible_triangular_number(NUMBER_OF_DIVISORS)
if __name__ == "__main__":
main() |
ff8e77362c377f1c5787f0cf3ced3491c6f83065 | MMuttalib1326/Binary-Heap | /BINARY HEAP.py | 4,155 | 3.765625 | 4 | # BINARY HEAP
class Heap:
def __init__(self,size):
self.customList=(size+1)*[None]
self.heapSize=0
self.maxsize=size+1
def peekofHeap(rootNode):
if not rootNode:
return
else:
return rootNode.custom[1]
def sizeofHeap(rootNode):
if not rootNode:
return
else:
return rootNode.heapSize
def levelorderTraversal(rootNode):
if not rootNode:
return
else:
for i in range(1,rootNode.heapSize+1):
print(rootNode.customList[i])
def heapifyTreeInsert(rootNode,index,heapType):
parentIndex=int(index/2)
if index<=1:
return
if heapType=="Min":
if rootNode.customList[index]<rootNode.customList[parentIndex]:
temp=rootNode.customList[index]
rootNode.customList[index]=rootNode.customList[parentIndex]
rootNode.customList[parentIndex]=temp
heapifyTreeInsert(rootNode,parentIndex,heapType)
elif heapType=="Max":
if rootNode.customList[index]>rootNode.customList[parentIndex]:
temp=rootNode.customList[index]
rootNode.customList[index]=rootNode.customList[parentIndex]
rootNode.customList[parentIndex]=temp
heapifyTreeInsert(rootNode,parentIndex,heapType)
def insertNode(rootNode,nodeValue,heapType):
if rootNode.heapSize+1==rootNode.maxsize:
return"The Binary Heap is full"
rootNode.customList[rootNode.heapSize+1]=nodeValue
rootNode.heapSize+=1
heapifyTreeInsert(rootNode,rootNode.heapSize,heapType)
return"The Value has been succefully completed"
def heapifyTreeExtrack(rootNode,index,heapType):
leftIndex=index*2
rightIndex=index*2+1
swapChild=0
if rootNode.heapSize<leftIndex:
return
elif rootNode.heapSize==leftIndex:
if heapType=="Min":
if rootNode.customList[index]>rootNode.customList[leftIndex]:
temp=rootNode.customList[index]
rootNode.customList[index]=rootNode.customList[leftIndex]
rootNode.customList[leftIndex]=temp
return
else:
if rootNode.customList[index] < rootNode.customList[leftIndex]:
temp=rootNode.customList[index]
rootNode.customList[index]=rootNode.customList[leftIndex]
rootNode.customList[leftIndex]=temp
return
else:
if heapType=="Min":
if rootNode.customList[leftIndex]<rootNode.customList[rightIndex]:
swapChild=leftIndex
else:
swapChild=rightIndex
if rootNode.customList[index]>rootNode.customList[swapChild]:
temp=rootNode.customList[index]
rootNode.customList[index]=rootNode.customList[swapChild]
rootNode.customList[swapChild]=temp
else:
if rootNode.customList[leftIndex]>rootNode.customList[rightIndex]:
swapChild=leftIndex
else:
swapChild=rightIndex
if rootNode.customList[index]<rootNode.customList[swapChild]:
temp=rootNode.customList[index]
rootNode.customList[index]=rootNode.customList[swapChild]
rootNode.customList[swapChild]=temp
heapifyTreeExtrack(rootNode,swapChild,heapType)
def extractNode(rootNode,heapType):
if rootNode.heapSize==0:
return
else:
extrecktedNode=rootNode.customList[1]
rootNode.customList[1]=rootNode.customList[rootNode.heapSize]
rootNode.customList[rootNode.heapSize]=None
rootNode.heapSize-=1
heapifyTreeExtrack(rootNode,1,heapType)
return extrecktedNode
def deleteEntireBH(rootNode):
rootNode.custom=None
newHeap=Heap(5)
insertNode(newHeap,4,"Max")
insertNode(newHeap,5,"Max")
insertNode(newHeap,2,"Max")
insertNode(newHeap,1,"Max")
extractNode(newHeap,"Max")
levelorderTraversal(newHeap)
print(deleteEntireBH(newHeap)) |
cba6f234a33e79c1153df6d8c5e1b6afca31b553 | SophiaStellaMary/Guvi | /Find factorial of a number.py | 126 | 4.0625 | 4 | '''Factorial of a number'''
fact=int(input())
factorial=1
for i in range(1,fact+1):
factorial=factorial*i
print(factorial)
|
baf7eb94b1f9502fa3fc51c24ca81b59aaf10660 | SophiaStellaMary/Guvi | /Program to reverse every word in the string .py | 134 | 3.984375 | 4 | '''Hunter 11 Program to reverse every word in the string'''
a=input().split()
for i in range(0,len(a)):
print(a[i][::-1],end=" ")
|
c6a3d3ed2b5f90ebcbfeeefef8237f9906e3f314 | SophiaStellaMary/Guvi | /Player 3 print a number and reverse.py | 62 | 3.8125 | 4 | '''print a number and reverse'''
a=input()
a=a[::-1]
print(a)
|
c2c1a711cfa510436b1ce96ca732a80b8fa890bf | SophiaStellaMary/Guvi | /Count the no.of.characters in string without counting the space .py | 202 | 4.0625 | 4 | ''' Count the no.of.characters in string without counting the space '''
character = input()
count = 0
for i in range(len(character)):
if(character[i]==" "):
continue
count=count+1
print(count)
|
2a0c7647885523f0205e52e95220e1dca5fb4da2 | SophiaStellaMary/Guvi | /calculate_the_power_of_a_number.py | 110 | 3.734375 | 4 | #calculate the power of a number N with given exponent(k)
a,b=input().split()
a=int(a)
b=int(b)
print(a**b)
|
a5816705dd924eee22232108936eb95840100f49 | bakker4444/string_and_list_practice | /stringsandlists.py | 581 | 3.96875 | 4 | # Find and Replace
words = "It's thanksgiving day. It's my birthday, too!"
print words.find("day")
print words.replace("day", "month")
# Min and Max
x = [2, 54, -2, 7, 12, 98]
print min(x)
print max(x)
# First and Last
x = ["hello", 2, 54, -2, 7, 12, 98, "world"]
print "First value in array x is :", x[0]
print "Last value in array x is :", x[-1]
print [x[0], x[-1]]
# New List
x = [19, 2, 54, -2, 7, 12, 98, 32, 10, -3, 6]
x.sort()
print x
# splitting in half
x_first_half = x[:len(x)/2]
x_second_half = x[len(x)/2:]
x_second_half.insert(0, x_first_half)
print x_second_half
|
b38cd4968d5754a2a3e26e2413c36f541a3f05c1 | skyline75489/leetcode | /longest-common-prefix.py | 426 | 3.515625 | 4 | class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ''
first = strs[0]
for i in range(0, len(first)):
for s in strs[1:]:
try:
if s[i] != first[i]:
return first[0:i]
except IndexError:
return first[0:i]
return first
|
d8ab6c5a43c79d55ec807270e90209d899765034 | ophd/HackerRankProblems | /Interview Prep Kit/Arrays/Minimum Swaps 2.py | 660 | 4.09375 | 4 | def minimumSwaps(arr):
'''
Counts the minimum number of swaps required to sort an array.
assumptions:
n = len(arr)
arr cotains all integers in interval [1, n]
'''
arr = [a - 1 for a in arr]
i = 0
swaps = 0
while i < len(arr) - 1:
if arr[i] != i:
j = arr[i]
arr[i], arr[j] = arr[j], arr[i]
swaps += 1
else:
i += 1
return swaps
if __name__ == '__main__':
xs = [[7, 1, 3, 2, 4, 5, 6],
[2, 3, 4, 1, 5],
[1, 3, 5, 2, 4, 6, 7]]
for x in xs:
print(f'A minimum of {minimumSwaps(x)} swaps are required to sort {x}.')
|
a89c52ac3c7833fbefbba1f1db07837463b9eadb | ophd/HackerRankProblems | /Interview Prep Kit/Dictionaries and Hashmaps/Count Triplets.py | 1,376 | 3.75 | 4 | def countTriplets(arr, r):
'''
Given an array of numbers and a common ratio,
find the number of triplets following a geometric progression,
such that arr[i] <= arr[j] <= arr[k],
arr[j] = r * arr[i],
arr[k] = r * r * arr[i] = r * arr[j]
i < j < k.
Note that, contrary to the examples given by Hacker Rank, the array
is not necessarily sorted.
A brute force method will time out when submitted.
constraints:
1 <= |arr| <= 10e5
1 <= r <= 10e9
1 <= arr[i] <= 10e9
'''
ahead = {}
potential = {}
triplets = 0
for val in arr:
val_next = r * val
if val in potential:
triplets += potential[val]
if val in ahead:
potential.setdefault(val_next, 0)
potential[val_next] = potential[val_next] + ahead[val]
ahead.setdefault(val_next, 0)
ahead[val_next] += 1
return triplets
if __name__ == '__main__':
r = [2, 3, 5, 6, 3, 1]
test = [[1, 2, 2, 4],
[1, 3, 9, 9, 27, 81],
[1, 5, 5, 25, 125],
[6, 216, 36, 6, 216, 36, 36, 216, 1296, 216],
[1, 3, 3, 9, 3, 9],
[1, 1, 1, 1, 1]
]
ans = [2, 6, 4, 15, 5, 10]
for ratio, array, answer in zip(r, test, ans):
print(answer == countTriplets(array, ratio)) |
5f489bb899465693b8cac6148798717290433fe6 | ophd/HackerRankProblems | /SortingAlgorithms.py | 2,921 | 3.578125 | 4 | import time
from functools import wraps
def timed_func(fn, n=1000):
@wraps(fn)
def do_n_times(*args, **kwargs):
time_start = time.perf_counter()
for _ in range(n):
result = fn(*args, **kwargs)
time_elapsed = time.perf_counter() - time_start
print(f'{fn.__name__}: {time_elapsed:0.2f} s')
return result
return do_n_times
# https://en.wikipedia.org/wiki/Sorting_algorithm
def quick_sort():
# https://en.wikipedia.org/wiki/Quicksort
pass
def bubble_sort(arr):
# https://en.wikipedia.org/wiki/Bubble_sort
swapped = True
n = len(arr)
while swapped:
swapped = False
for i in range(1, n):
if arr[i] < arr[i-1]:
arr[i-1], arr[i] = arr[i], arr[i-1]
swapped = True
return arr
def insertion_sort():
# https://en.wikipedia.org/wiki/Insertion_sort
pass
def heap_sort():
# https://en.wikipedia.org/wiki/Heapsort
pass
def counting_sort(arr):
# https://en.wikipedia.org/wiki/Counting_sort
# Knowing the range of arr would speed up this algorithm as it would
# avoid the extra pass through the array to determine the min/max values
arr_min, arr_max = None, None
for item in arr:
if arr_min is None or item < arr_min:
arr_min = item
if arr_max is None or item > arr_max:
arr_max = item
freqs = (arr_max - arr_min + 1) * [0]
for item in arr:
freqs[item - arr_min] += 1
for i in range(1, len(freqs)):
freqs[i] = freqs[i-1] + freqs[i]
freqs = [0] + freqs[:-1]
sorted_arr = len(arr) * [None]
for item in arr:
sorted_arr[freqs[item - arr_min]] = item
freqs[item - arr_min] += 1
return sorted_arr
def radix_sort(arr):
# https://en.wikipedia.org/wiki/Radix_sort#Least_significant_digit_radix_sorts
pass
def merge_sort(arr):
# https://en.wikipedia.org/wiki/Merge_sort
n = len(arr)
if n < 2:
return arr
mid = n // 2 + n % 2
L, R = merge_sort(arr[:mid]), merge_sort(arr[mid:])
i = j = 0
n, m = len(L), len(R)
merged_arr = []
while i < n and j < m:
if L[i] <= R[j]:
merged_arr.append(L[i])
i += 1
else:
merged_arr.append(R[j])
j += 1
while i < n:
merged_arr.append(L[i])
i += 1
while j < m:
merged_arr.append(R[j])
j += 1
return merged_arr
def tim_sort():
# https://en.wikipedia.org/wiki/Timsort
# https://github.com/python/cpython/blob/dd754caf144009f0569dda5053465ba2accb7b4d/Objects/listsort.txt
pass
if __name__ == "__main__":
tests = [[56, 24, 35, 3, 100, 88, 22, 89, 12, 88, 99, 6, 73]]
functions = [bubble_sort, merge_sort, counting_sort]
for test in tests:
for function in functions:
print(timed_func(function, 10000)(test))
|
95083c90b4cafcb776e2754c477f561a1f57544c | ophd/HackerRankProblems | /Python/Validating Postal Codes.py | 436 | 3.84375 | 4 | import re
def validate_postal_code(postal_code):
return bool(re.match(r'[1-9]\d{5}$', postal_code)
and len(re.findall(r'(\d)(?=.\1)', postal_code)) < 2
)
if __name__ == "__main__":
postal_codes = ['121426', '523563', '552523', '110000']
answers = [True, True, False, False]
for postal_code, answer in zip(postal_codes, answers):
print(validate_postal_code(postal_code) == answer) |
93b57a19b934d732e35cab48950dfd4ba68a73d0 | harvi7/Leetcode-Problems-Python | /Graph/course_schedule_ii.py | 1,171 | 3.578125 | 4 | # https://leetcode.com/problems/course-schedule-ii/discuss/59425/My-python-DFS-recursive-solution-(same-algorithm-for-207-and-210)
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = [[] for i in range(numCourses)]
visit = [0 for i in range(numCourses)]
res = []
for edge in prerequisites:
graph[edge[0]].append(edge[1])
i = 0
while i < numCourses:
if len(graph[i]) == 0:
res += i,
visit[i] = -1
i += 1
def dfs(x, res):
if visit[x] == -1:
return False
if visit[x] == 1:
return True
visit[x] = 1
for v in graph[x]:
if dfs(v, res):
return True
visit[x] = -1
res.append(x)
return False
for i in range(numCourses):
if dfs(i, res):
return []
return res |
48f7e3f089d5f57920f6ecd7068ba0703b86eb0e | harvi7/Leetcode-Problems-Python | /Stack/remove_all_adjacent_duplicates_in_string.py | 237 | 3.515625 | 4 | class Solution:
def removeDuplicates(self, S: str) -> str:
sb = []
for ch in S:
if sb and ch == sb[-1]:
sb.pop()
else:
sb.append(ch)
return ''.join(sb) |
ced392f4c2e4436737e96392698a0335cbd36655 | harvi7/Leetcode-Problems-Python | /Tree/maximum_depth_of_n-ary_tree.py | 711 | 3.625 | 4 | class Solution:
def maxDepth(self, root: 'Node') -> int:
# BFS Solution
# queue, depth = [], 0
# if root: queue.append((root, 1))
# depth = 0
# for (node, level) in queue:
# depth = level
# queue += [(child, level+1) for child in node.children]
# return depth
if root is None: return 0
return self.get_max_depth(root, 1, 1)
# DFS Solution
def get_max_depth(self, node, depth, max_depth):
if node is None: return max_depth
max_depth = max(depth, max_depth)
for child in node.children:
max_depth = self.get_max_depth(child, depth + 1, max_depth)
return max_depth |
899382625dbbf83133ac3335eb7af6b5a8eed32e | harvi7/Leetcode-Problems-Python | /Heap/sort_characters_by_frequency.py | 367 | 3.671875 | 4 | class Solution:
def frequencySort(self, s: str) -> str:
char_map = {}
for c in s:
char_map[c] = char_map.get(c, 0) + 1
sorted_map = sorted(char_map, key = char_map.get, reverse = True)
result = ""
for count in sorted_map:
result += count * (char_map[count])
return result |
b8ab2035e439f95dad870724662495a6eae7c50c | harvi7/Leetcode-Problems-Python | /Design/implement_trie.py | 1,445 | 4.0625 | 4 | class TrieNode:
isWord = False
children = []
def __init__(self, val):
self.val = val
self.children = [None] * 26
self.isWord = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode("")
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for i in range(len(word)):
c = word[i]
if not node.children[ord(c) - ord('a')]:
node.children[ord(c) - ord('a')] = TrieNode(c)
node = node.children[ord(c) - ord('a')]
node.isWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for i in range(len(word)):
c = word[i]
if not node.children[ord(c) - ord('a')]:
return False
node = node.children[ord(c) - ord('a')]
return node.isWord
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for i in range(len(prefix)):
c = prefix[i]
if not node.children[ord(c) - ord('a')]:
return False
node = node.children[ord(c) - ord('a')]
return True |
deaff7e6f2a487fed95ebde53b182c140de9d334 | harvi7/Leetcode-Problems-Python | /Two Pointers/backspace_string_compare.py | 472 | 3.5 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
new_s, new_t = [], []
for i in S:
if i == '#':
if new_s:
new_s.pop()
else:
new_s.append(i)
for j in T:
if j == '#':
if new_t:
new_t.pop()
else:
new_t.append(j)
return new_s == new_t |
55898d276abca50526eea76f250a8dca106e701d | harvi7/Leetcode-Problems-Python | /Hash Table/shortest_completing_word.py | 611 | 3.53125 | 4 | class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
def count(word):
result = [0] * 26
for letter in word:
result[ord(letter) - ord('a')] += 1
return result
def dominates(c1, c2):
return all(x2 <= x1 for x1, x2 in zip(c1, c2))
ans = ""
target = count(c.lower() for c in licensePlate if c.isalpha())
for word in words:
if (not ans or (len(word) < len(ans))) and dominates(count(word.lower()), target):
ans = word
return ans |
ed5145ae23fd3fc3fe3a974b6fd9bc6751421825 | harvi7/Leetcode-Problems-Python | /Backtracking/increasing_subsequences.py | 922 | 3.625 | 4 | # https://leetcode.com/problems/increasing-subsequences/discuss/804364/Python-backtrack-with-Set
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
if not nums:
return []
result = set()
leng = len(nums)
def backtrack(currArray, start):
if len(currArray) > 1:
t = tuple(currArray)
if t not in result:
result.add(t)
if start >= leng:
return
for i in range(start, leng):
currLeng = len(currArray)
if currLeng >0 and nums[i] < currArray[currLeng-1]:
continue
currArray.append(nums[i])
backtrack(currArray, i + 1)
currArray.pop()
backtrack([], 0)
return result
|
b8983f7e35e7722b0744cc98e981109c1d9dfcc5 | MikiEEE/SmallOS | /SmallPackage/SmallPID.py | 1,332 | 3.578125 | 4 |
class SmallPID():
'''
@class smallPID() - Creates and keeps track of avialable
Process ID's
'''
def __init__(self, max=2**16):
'''
@function __init__() - Initializes essential maintenence
structures.
@param max - int - The max number of process ID's.
Valid process ID's are 0 - (max - 1).
@return - void
'''
self.pastPid = 0
self.maxPID = max
self.usedPID = set()
return
def newPID(self):
'''
@function newPID() - Creates a new valid PID.
@return - int - positive integer on succes
-1 on failure.
'''
if len(self.usedPID) < self.maxPID:
pid = self.pastPid
while pid%self.maxPID in self.usedPID: pid+=1
self.usedPID.add(pid%self.maxPID)
if self.pastPid >= self.maxPID:
self.pastPid = 0
self.pastPid = pid
return pid%self.maxPID
else:
return -1
def freePID(self,pid):
'''
@function freePID - removes the pid from the used
pid set() making the pid available for future
use.
@return - void
'''
if pid in self.usedPID:
self.usedPID.remove(pid)
return |
aa46cbc941ed982725f2b8ff76e1dd93aa46e3d6 | adam-suwei/python | /1 基础/4 变量.py | 471 | 3.828125 | 4 |
x =10
x=x+10
print('x = ',x)
# 变量交换是值传递 而不是地址传递
a = 'abc'
b = a
a = 'xyz'
print('abc = ',b)
print('xyz = ',a)
#/除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数:
a = 10/3
print(a)
# //,%操作结果是整数
print(r'取商//\n:',10//3)
print(r'取余数\%',10%3)
f = 456.789
qqq = 123 #qqq is int [可变类型,类型可变]
qqq = b'abc' #qqq is bytes
print('qqq in bytes is:',qqq)
|
dd6b844f1c811bde00037305e1aee0c4adaff696 | adam-suwei/python | /1 基础/8 list数据类型.py | 4,209 | 3.75 | 4 | # Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。
#赋值
classmete = ['adam','peter','joy','judy']
classmete
l = list('01234567')
l = list(range(8)) # 不包括8
#获得长度
len(classmete) #4
#按索引取值
classmete[0]
classmete[1]
classmete[2]
classmete[3]
classmete[4] #oor
# 取得最后一个元素
classmete = ['adam','peter','joy','judy']
l1 = len(classmete)
classmete [l1-1]
classmete[-1]
classmete[-2] #可以-2 ^_^
#倒数是可以从1开始数到len的,倒数时下标不用减去1
classmete = ['adam','peter','joy','judy']
l1 = len(classmete)
l2=5
if l1<l2: # 不用减去1
'oor'
else:
classmete[-3]
#list是一个可变的有序表,所以,可以往list中追加元素到末尾:
boys = ['adam','peter','joy','judy']
boys.append('test')
boys
boys[len(boys):]
#extend 添加list
boys = ['adam','peter','joy','judy']
boys.extend(['adam','b'])
boys
# ['adam', 'peter', 'joy', 'judy', 'adam', 'b']
#清空list
boys = ['adam','peter','joy','judy']
boys
boys.clear()
boys #[]
# 插入中间插入
boys = ['1','2','3','4'] #一个list里面可以各种类型
boys.insert(1,99) #['1', 99, '2', '3', '4']
boys
# 可以倒数着插入
boys.insert(-1,'b') # ['1', '2', '3', 'b', '4']
boys
#要删除list末尾的元素,用pop()方法: pop()=pop(-1)
boys = ['1','2','3','4']
boys.pop() #['1', '2', '3']
boys
boys = ['1','2','3','4']
boys.pop(0) #['2', '3','4']
boys
boys.pop(4) # Error oor
boys
boys = ['1','2','3','4']
boys.pop(-2) #可以倒数删除 #['1', '2', '4']
boys
# remove 删除字符,pop删除位置
boys = ['1a','2','1a','4']
boys.remove('1a') #['2', '1a', '4']
boys
boys.remove('a') # Error not in list
boys
#替换
boys = ['1','2','3','4']
boys[-2] = '3a'
boys #['1', '2', '3a', '4']
boys = ['1','2','3','4']
boys[3] = '4a'
boys #['1', '2', '3', '4a']
#多维数组
multA =['a',['b1','b2',['b3a','b3b']],'c']
multA[0] #'a'
multA[1] #['b1', 'b2']
multA[1][1]
listA = multA[1]
listA[1] #'b2'
strB = multA[1][2][0]
strB #'b3a'
#index 计算某元素出现第一个位置
boys = ['1a','2','1a','4']
i=boys.index('1a')
i #0
#index 从片段中找出现位置
boys = ['1','2','1','4']
i= boys.index('1',1,3) # 2 1 4中找
i #return 2 返回1 2 1 4中的位置
#count 计算某元素出现的次数
boys = ['1a','2','1a','4']
i=boys.count('1a')
i #return 2
#sort 排序 sort() 没有返回值,修改了原list
boys = ['a','b','d','c']
boys.sort()
boys #['a', 'b', 'c', 'd']
boys = ['1','a','2','b']
boys.sort()
boys #['1', '2', 'a', 'b']
boys[2] # a 而不是2 说明list数据位置变化了
boys = [1,'a',2,'b']
boys.sort()
boys #不支持多类型之间排序
#reverse() 反转列表中的元素 修改原数组
boys = ['a','b','c','d']
boys.reverse()
boys #['d', 'c', 'b', 'a']
boys = ['a','b','c','d']
boyss=boys[::-1] #反转取值
boys #['a', 'b', 'c', 'd']
boyss #['d', 'c', 'b', 'a']
#copy 直接复制 = :
boys = ['a','b','c','d']
boya=boys.copy()
boyss=boys[:]
boya
boyss
#pop 作为堆栈 有返回值
boys = ['a','b','c','d']
str = boys.pop()
boys
str
# 使用deque做序列,list从尾部效率高,从头部pop()效率很低(因为所有item位置都要移动)
from collections import deque
boys = ['a','b','c','d']
deque = deque(boys)
deque.popleft()
boys #boys没有变化 ['a','b','c','d']
deque #deque [b','c','d']
boys
# 多维赋值
boys=[1,2]
boys[1]=['a','b']
boys
boys=[1,['a','b']]
boys[1].append('c')
boys
boys = [1,['a','b']]
boys[1][1]
boys[1][1]=[31,42]
boys #[1, ['a', [31, 42]]]
boys=[1,2]
boys.append(['a','b','c'])
boys
# list()方法可以把序列转换成list 列表才能打印出来
list(range(10))
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 遍历list
l = [1,2,3]
for i in l:
print(i,type(i))
#list赋值给三个变量
a,b,c =[1,2,3]
a
b
c
# 1
# 2
# 3
|
c75206afa72c2d8f89373f41a87367b57ea10728 | adam-suwei/python | /1 基础/12 dict 数据结构 .py | 4,494 | 3.71875 | 4 | # dict 就是java中的map
#
# 构造推导式
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e #True
d = {x: x**2 for x in (2, 4, 6)}
d #{2: 4, 4: 16, 6: 36}
#看看主类
d = {'a':1,'b':2,'3':3}
type(d) #<class 'dict'>
type(d.keys()) #<class 'dict_keys'>
type(d.values()) #<class 'dict_values'>
type(iter(d)) #<class 'dict_keyiterator'>
#dict() 仅仅使用与 Key 是字符串时
d = dict(a=1,b=2,c=3) #,1 = 1 报错
d #{'a': 1, 'b': 2, 'c': 3} 1 =1 报错
d = dict(sape=4139, guido=4127, jack=4098)
d
#取值
d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
e = d['a']
# e 1
d = {'a':1,'b':2}
e = d.get('a')
e #1
#取不到 打印None
d = {'a':1,'b':2}
e =d.get('e')
print('==',d.get('e')) # == None Python的交互环境不显示结果
# #has_key() key里面是否有值
# d = {'a':1,'b':2}
# print('?',d.has_key('1'))
# copy() 值复制,各玩各的
d = {'a':1,'b':2,'c':3}
d1 =d.copy()
d1
d1['a'] =11
d['a'] = 10
d
d1
# >>> d
# {'a': 10, 'b': 2, 'c': 3}
# >>> d1
# {'a': 11, 'b': 2, 'c': 3}
# fromKeys() 把老dirt中的key拿来,values不要
d = {'a':1,'b':2,'c':3}
c = c.fromkeys(d)
c #{'a': None, 'b': None, 'c': None}
# iter(d) = iter(d.keys())
d = {'a':1,'b':2,'c':3}
iter(d) # is object at 0x0000000001E19E00>
for i in iter(d):
print(i)
# a
# b
# c
for i in iter(d.values()):
print(i)
# 1
# 2
# 3
# reversed(d) == reversed(d.keys())
d = {'a':1,'b':2,'c':3}
for i in reversed(d.keys()):
print(i)
# c
# b
# a
#指定找不到Key时返回 ^_^
d = {'a':1,'b':2}
e = d.get('e','^_^')
e #'^_^'
# setdefault()指定找不到时返回默认值
d = {'a':1,'b':2}
d.setdefault('black',0)
d #{'a': 1, 'b': 1, 'black': 0}
d = {'a':1,'b':2}
len(d) # 2
len(d.items()) # 2
len(d.keys()) # 2
len(d.values()) # 2
#修改
d['a'] = 'a1'
# d {'a': 'a1', 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
#重复的后者覆盖前者
a ='a'
d = {'a':1,a:2,'c':3,'d':4,'e':5,a:6}
d #{'a': 6, 'c': 3, 'd': 4, 'e': 5}
# keys() values()方法 items()方法 d.这三个方法都是建立新对象,两次同样的keys() 对象地址不同 == 返回False
d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
print('d.keys() = ',d.keys()) #dict_keys(['a', 'b', 'c', 'd', 'e', 'f'])
print('d.values() = ',d.values()) #dict_values([1, 2, 3, 4, 5, 6])
print('d.items() = ',d.items()) #dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6)])
# in 判断是否存在key中
d = {'a':1,'b':2,}
bl = 'a' in d
print('a in d ?',bl) # True
bl = 'a' not in d
print('a not in d ?',bl) # True
k = 'a' in d.keys()
print('a in d.keys() ?',k) # True
v = 1 in d.values()
print(' 1 in d.values()?',v) # True
# 删除key
d = {'a':1,'b':2}
d.pop('a')
d #{'b': 2}
d = {'a':1,'b':2}
del d['a']
d #{'b': 2}
d.clear()
d #{}
del d
d # name 'd' is not defined
#删除最后一对item
d = {'a':1,'b':2}
d.popitem()
d
# 和list比较,dict有以下几个特点:
# 查找和插入的速度极快,不会随着key的增加而变慢;
# 需要占用大量的内存,内存浪费多 【牺牲存储求速度】
# dict的key必须是不可变对象 字符串、整数 tuble等
d = {['a','b']:12,'c':3} # err key不支持list 不允许设置
d = {('a','b','c'):123,'d':4} #{('a', 'b', 'c'): 123, 'd': 4} 支持元组 tuple
d
d = {'a':1,'b':2}
key = [1,2,3,]
d[key] #不允许调用
#update() 取合集,相同key的覆盖
d1 = {'a':1,'b':2}
d2 = {'a1':1,'b':3}
d1.update(d2) #
d1 #{'a': 1, 'b': 3, 'a1': 1}
# 遍历 items()
d = {'a':1,'b':2,'c':3}
for k,v in d.items():
print('Key:%s is %s' %(k,v) )
# Key:a is 1
# Key:b is 2
# Key:c is 3
# 遍历 keys()
d = {'a':1,'b':2,'c':3}
for k in d.keys():
print('Key : %s ' %(k) )
# Key : a
# Key : b
# Key : c
# 遍历 values()
d = {'a':1,'b':2,'c':3}
for v in d.values():
print('Value : %s ' %(v) )
# Value : 1
# Value : 2
# Value : 3
# enumerate() 获取位置
d = {'a':1,'b':2,'3':3}
for i,v in enumerate(d.values()):
print(' pose %d is %s' %(i,v))
# pose 0 is 1
# pose 1 is 2
# pose 2 is 3
d = {'a':1,'b':2,'3':3}
for i,v in enumerate(d.items()):
print(' pose %d is %s' %(i,v))
# pose 0 is ('a', 1)
# pose 1 is ('b', 2)
# pose 2 is ('3', 3)
#list()
d = {'a':1,'b':2,'3':3}
l = list(d.items())
l #[('a', 1), ('b', 2), ('3', 3)]
|
2d8476fd816fa5a24c0bff292c189124d14d3535 | adam-suwei/python | /7 面向对象高级编程/4 定制类.py | 3,015 | 3.953125 | 4 | #----------------------------------------------------
# class 中的 __str__
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return ('hi~ I am a student ,my name is: %s' % self.name)
__repr__ = __str__
s = Student('a gang')
print(s)
# hi~ I am a student ,my name is: a gang
s
# 直接显示变量调用的不是__str__(),而是__repr__()
# haha ! I am a student ,my name is a gang
# __str__()返回用户看到的字符串,而__repr__()返回程序开发者看到的字符串,也就是说,__repr__()是为调试服务的。
#----------------------------------------------------
# class 中的 __iter__
class Fib(object):
def __init__(self):
self.a,self.b =0,1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b,self.a+self.b
if self.a>10000:
raise StopIteration
return self.a
for n in Fib():
type(n)
print(n)
#----------------------------------------------------
# __getitem__ 根据下标获取数据
class Fia(object):
def __getitem__(self,n):
a,b = 1,1
for x in range(n):
a,b =b,a+b
return a
f = Fia()
f[9]
# 55
class Fic(object):
def __getitem__(self,n):
if isinstance(n,int):
a,b =1,1
for x in range(n):
a,b =b,a+b
return a
if isinstance(n,slice):
start = n.start
stop = n.stop
if start is None:
start = 0
a,b = 1,1
L =[]
for x in range(stop):
if x >= start:
L.append(a)
a,b = b,a+b
return L
fc = Fic()
fc[9]
# 55
l = fc[1:10]
l
# [1, 2, 3, 5, 8, 13, 21, 34, 55]
#----------------------------------------------------
#__setitem__() __delitem__()
# _getattr__ 当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性,
class Sta(object):
def __init__(self):
self.name = 'Micheal'
def __getattr__(self,attr):
if attr == 'score':
return 99
elif attr =='name':
return 'adam'
elif attr == 'age':
return lambda:25 #注意这是一个方法
raise AttributeError('\'Sta\' object has no attribute \'%s\'' %attr) #没有这样则返回None
s = Sta()
s.name #找到了name属性就不走getattr方法了
s.score
s.age()
# 'Micheal'
# 99
# 25
s.height
# 'Sta' object has no attribute 'height'
#----------------------------------------------------
# 把对象当成方法调用 这么一来,我们就模糊了对象和函数的界限
class Studena(object):
def __init__(self,name):
self.name = name
def __call__(self):
print('My name is %s.' % self.name)
s = Studena('adam')
s()
#callable 判断是否是函数
callable(Studena('a'))
# True
callable(range(10))
# False
|
22bf42d158dd7ae6bbb6eea1ba7c1b3d462f4d9c | joonyi/ProjectEuler | /prob26.py | 520 | 3.53125 | 4 | """
0.1(6) means 0.166666..., and has a 1-digit recurring cycle.
It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle
in its decimal fraction part.
"""
# Unsolved
a = 1
b = 7
digits = 8
for i in range(digits):
n = a/b
print(str(a)+'/'+str(b)+'='+str(n))
a = (a % b) * 10
# print(n)
def cycle(b):
a = 1
t = 0
while True:
a = a * 10 % b
t += 1
if a == 1:
break
return t
|
946fb66065cc14b9c0c3575ff728c65a398c8d95 | joonyi/ProjectEuler | /prob30.py | 827 | 3.796875 | 4 | """
Digit fifth powers
Problem 30
Surprisingly there are only three numbers that can be written as the sum of fourth powers
of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers
of their digits.
"""
# A max number with d digits is n = d*9^5 and it must be bounded by number-length interval
# 10^(d-1) < d*9^5 < 10^d
fifth = []
larger = []
for i in range(10,354294+1):
total = 0
n = i
while n > 0:
tmp = n % 10
total += tmp**5
n //= 10
if total == i:
fifth.append(i)
elif total < i:
larger.append(i)
# print(fifth)
print(larger[:100]) |
244de02735c1b990fa273175475e8646c363dfef | kookou/python_machine_learning_study | /sba_api_01/contacts/calculator.py | 667 | 3.6875 | 4 | class Claculator:
def__init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def sum(self):
return self.num1 + self.num2
def sub(self):
return self.num1 = self.num2
def mul(self):
return self.num1 * self.num2
def div(self):
return self.num1 / self.num2
if __name__ == '__main__':
calc = Claculator(4,6) # num1 = 4 , num2 = 6
sumResult = cala.sum()
re2 = cala.sub()
re3 = cala.mul()
re4 = cala.div()
print('덧셈 결과' +format(sumResult))
print('뺄셈 결과' + format(re2))
print('곱셈 결과' + format(re3))
print('나눗셈 결과' + format(re4)) |
63b59fa07c0e8df9f0cf9cb1bc76100a68b8ba7d | pulgamecanica/pw-python-03 | /exercicio_1/analisa_ficheiro/acessorio.py | 381 | 3.84375 | 4 | import os
def pede_nome():
while True:
fileName = input("Please Enter the file name: ");
if fileName.split(".")[-1] != "txt":
print("The file should be a '.txt' file!")
continue
elif not os.path.exists(fileName):
print(f"The file '{fileName}' doesn't exists")
continue
else:
return fileName
def gera_nome(fileName):
return fileName.replace(".txt", ".json") |
c946a796f2619483bba6b0593a3e3bd8295c7bc7 | JeanCarlosSC/codigos-varios | /misPrimerosProgramas/python/range/src/range.py | 195 | 4.03125 | 4 | print("Printing current and previous number sum in a given range(10)")
b=0
for i in range(10):
if(i>0):
b=i-1
c=i+b
print("Current Number", i,"Previous Number", b, "Sum:", c)
|
c92b578655f3f0e82e090746691d2ba7d4472658 | hwsonnn/python_crawling | /희원_python/0204___datetime.py | 412 | 3.625 | 4 | from datetime import date, time, datetime, timedelta
#ctime = datetime.now()
ctime = datetime.now() - timedelta(days=1)
# - timedelta(days=1) 을 추가함으로써 어제 날짜 출력됨.
print(ctime)
print(type(ctime))
print(ctime.year)
print(ctime.month)
print(ctime.day)
print(ctime.strftime('%Y%m%d'))
|
021d84be95ceabe759fe84c0d5eeee54056395dc | hwsonnn/python_crawling | /SQL/07(교수님)/03.py | 718 | 3.75 | 4 | data = 1234
print(type(data))
print("-"*20)
#정수->문자열
data = str(data)
print(type(data))
print("자리수:", len(data))
print("마지막:", data[-1])
print("-"*20)
#문자열->바이트문자열
data = data.encode()
print(type(data))
print(data)
print("-"*20)
#바이트문자열->decoding문자열
data = data.decode("utf-8")
print(type(data))
print(data)
print("-"*20)
#바이트문자열->문자열
# data = str(data)
# print(type(data))
# print(data)
# print("-"*20)
data = list(data)
print(type(data))
print(data)
#리스트->문자열
data = "".join(data)
print(type(data))
print(data)
#문자열->실수
data = float(data)
print(type(data))
print(data) |
7b5004fcacaf06e8b5c292c8aa5f3394e0725b0a | hwsonnn/python_crawling | /희원_python/0204.py | 1,599 | 3.5625 | 4 | from urlToStr2 import urlToStr
from bs4 import BeautifulSoup
data = urlToStr('https://movie.daum.net/boxoffice/yearly?year=2019')
import matplotlib.pyplot as plt
#한글 폰트 사용
from matplotlib import font_manager, rc
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
def star(data):
bs=BeautifulSoup(data, 'html.parser')
lis=bs.select('#mArticle ul li')
ranklist=[] # 공백 리스트 하나 생성 ==> 그래프를 만들 자료를 넣기 위해
for li in lis:
taga=li.select_one('.desc_boxthumb')
if taga:
rank = float(taga.select_one('.emph_grade').text)
ranklist.append(rank)
print(rank)
print('-'*30)
print(type(lis)) # type 'list'
print(len(lis))
return ranklist
if __name__=="__main__":
s = int(input('시작년도 입력(ex)2019) : '))
f = int(input('종료년도 입력(ex)2020) : '))
if s > f :
temp = s
s = f
f = temp
print('시작=>', str(s), ', 종료=>', str(f))
labels = []
ylist = []
for y in range(s,f+1) :
url='https://movie.daum.net/boxoffice/yearly?year='+str(y)
print(url)
data=urlToStr(url)
ranklist=star(data)
ylist.append(ranklist)
labels.append(y)
for i in range(len(ylist)) :
plt.plot(ylist[i], label=labels[i])
plt.legend()
plt.show()
|
331c75869fa0bd334a73dbdbd128d9207a14763b | hwsonnn/python_crawling | /희원_python/0205_datatype3.py | 962 | 4 | 4 | ###### 파이썬 data type
#딕셔너리(dictionary) : 키와 값의 쌍
dic = {'a' : 1, 'b' : 2, 'c' : 3}
print(dic['a'])
dic['d'] = 4 # list와 tuple과 달리 순서가 정해져있지 않으므로
# append 쓸 필요 없음.
# 추가
dic['b'] = 4 # 수정
print(dic)
print('-'*30)
for item in dic :
print(item, '=>', dic[item])
print('-'*30)
for item in dic.items() :
print(item) # tuple 형태로 출력되는 것 확인
print('-'*30)
for key, value in dic.items() :
print(key, '=>', value)
print('-'*30)
for key in dic.items() :
print(key) # item 과 동일 출력 확인 (즉, tuple 형태)
print('-'*30)
for value in dic.items() :
print(value) # item 과 동일 출력 확인 (즉, tuple 형태)
|
9436d4c28c42a68726701aa2f5e0b498c0a761fe | hwsonnn/python_crawling | /pythoncrawling-master/07/02_file3.py | 245 | 3.59375 | 4 | def fileToStr(filename) :
#파일 열기
f = open(filename, "r", encoding="utf-8")
data = f.read()
#파일 종료
f.close()
return data
fname = input("파일명을 입력하세요.")
data = fileToStr(fname)
print(data)
|
3aad29f567bca81931caf96fab54c14b262da6bb | SilasPillsbury/Othello | /Othello.py | 952 | 3.65625 | 4 | b =[[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 2, 0, 0, 0],
[0, 0, 0, 2, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]
def play(b):
'Things'
return None
def check_playable(player,location,board):
"""
Player - int 1 or 2, location - length 2 index,
board - current board state, has nested indexes
"""
playable = False
if b[location[0]][location[1]] != 0:
return playable
#performs check if spot is empty
for x in board[location[0]][location[1]+1:8]:
if x == abs(3-player):
playable = True
continue
if x == 0:
playable = False
break
if x == player:
break
if playable:
return playable
for entry in range(8-location[1]):
y = board[entry][location[1]]
|
6d510ee1145d9bf01432ae267104cb9c6fd59e33 | sraj50/plexus-challange | /app/Overflow.py | 1,749 | 3.734375 | 4 | from collections import deque
from .Glass import Glass
def find_glass(i: int = 0, j: int = 0, k: float = 0) -> float:
glass = Glass()
glass.fill(k)
if j > i:
raise Exception(f"j cannot be greater than i for index (i={i}, j={j})")
index_map: dict = map_index(glass)
node = index_map.get((i, j))
if node is None:
print(f"Could not find Glass (i={i}, j={j})")
return 0
print(f"Found! Glass (i={i}, j={j}): {node.water}")
return node.water
def traversal(glass: Glass) -> tuple:
q = deque()
levels = []
q.append((glass, 0, True))
n_glasses = 0
total_water = 0
while len(q) > 0:
node, depth, row_end = q.popleft()
if node is None:
continue
while len(levels) < depth + 1:
levels.append([])
level = levels[depth]
level.append(node)
total_water += node.water
n_glasses += 1
entry = (node.left_child, depth + 1, False)
q.append(entry)
if row_end:
entry = (node.right_child, depth + 1, True)
q.append(entry)
return levels, total_water, n_glasses
def visualise(glass: Glass):
levels, total_water, n_glasses = traversal(glass)
for i, row in enumerate(levels):
row_num = str(i).zfill(3)
str_arr = [f"Row {row_num}: "]
for x in row:
str_arr.append(f"{x.water:.2f}")
print(" ".join(str_arr))
print(f"N. Glasses: {n_glasses}")
print(f"Total Water: {total_water}")
def map_index(glass: Glass) -> dict:
levels, total_water, n_glasses = traversal(glass)
d = {}
for i, row in enumerate(levels):
for x in row:
d[(i, row.index(x))] = x
return d
|
0bb02c4ac61dd820912a0326d626da24ebb05442 | GaryGky/Machine-Learning | /Kanada-Project/DeepCNN.py | 2,235 | 3.71875 | 4 | # Author By Gary1111
import numpy as np
import pandas as pd
from keras import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
train = pd.read_csv("data/DataPre/train_XY.csv", index_col=False)
test = pd.read_csv('data/DataPre/test.csv', index_col=False)
test.rename(columns={"Unnamed: 0": 'id'}, inplace=True)
test['id'] = list(range(1, 10001))
train_x = train.drop(['id', 'label'], axis=1) # 得到训练特征
train_y = train['label'] # 得到训练标签
test_x = test.drop('id', axis=1)
test_x = test_x / 255
train_x = train_x / 255
train_y = train_y.to_numpy()
train_feature = train_x.to_numpy().reshape((-1, 28, 28, 1))
test_feature = test_x.to_numpy().reshape((-1, 28, 28, 1))
print(train_feature.shape, test_feature.shape)
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
classifier.add(Conv2D(16, (3, 3), input_shape=(28, 28, 1), activation='relu'))
classifier.add(Conv2D(32, kernel_size=3, padding="same", activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Dropout(0.25))
classifier.add(Conv2D(64, kernel_size=3, padding="same", activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Dropout(0.25))
classifier.add(Conv2D(128, kernel_size=3, padding="same", activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Dropout(0.25))
classifier.add(Conv2D(256, kernel_size=3, padding="same", activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Dropout(0.25))
classifier.add(Flatten())
classifier.add(Dense(256, activation='relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(10, activation='softmax'))
# Compiling the ANN
classifier.compile(loss='sparse_categorical_crossentropy', optimizer="Adam", metrics=['accuracy'])
# Fitting the ANN to the Training set
classifier.fit(train_feature, train_y, batch_size=1, epochs=100)
# Part 3 - Making predictions and evaluating the classifier
# Predicting the Test set results
y_pred = classifier.predict(test_feature)
results = np.argmax(y_pred, axis=1)
data_out = pd.DataFrame({'id': range(1, 10001), 'label': results})
data_out.to_csv('submission.csv', index=None)
|
b41cccdba55a6a96a52e23b9943ac87748d05842 | ChoiHeon/algorithm | /02_백준/[11866] 요세푸스 문제 0.py | 345 | 3.53125 | 4 | # https://www.acmicpc.net/problem/11866
"""
"""
from collections import deque
N, K = map(int, input().split())
queue = deque()
for i in range(1, N+1):
queue.append(i)
answer = []
while queue:
for _ in range(K-1):
queue.append(queue.popleft())
answer.append(str(queue.popleft()))
print('<' + ", ".join(answer) + '>')
|
4ec7c34c857e4c9281d07edb44e3a0db34190ff3 | ChoiHeon/algorithm | /04_2020 카카오 신입 개발자 블라인드 채용 1차 코딩 테스트/04_가사 검색 (효율성 100% 통과).py | 2,041 | 3.5 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/60060
"""
효울성 100% 통과를 하기 위해 trie 자료구조를 사용
query 를 Trie 에 저장할 경우 효율이 떨어지므로 (bfs 탐색을 해야 하므로)
word 를 저장
* query 의 길이
- Trie 객체를 원소로 가지는 리스트를 생성
- word 의 길이를 인덱스로 하는 Trie 객체에 삽입
- query 의 길이를 인덱스로 하는 Trie 객체에서 해를 찾음
* 추가 가능 조건
- query 의 중복이 가능
- dict()를 사용하여 동일한 query 를 갖는 인덱스들을 저장
- set()을 사용하여 query 의 중복을 제거
"""
from collections import deque
class Node:
def __init__(self, key):
self.key = key
self.cnt = 0
self.children = {} # key : value = character : Node
class Trie:
def __init__(self):
self.head = Node(key=None) # key = None, cnt = 0
def insert_string(self, string):
cursor = self.head
for c in string:
if c not in cursor.children.keys():
cursor.children[c] = Node(key=c)
cursor.cnt += 1
cursor = cursor.children[c]
cursor.cnt += 1
def search(self, prefix):
cursor = self.head
for c in prefix:
if c not in cursor.children.keys():
return 0
cursor = cursor.children[c]
return cursor.cnt
def solution(words, queries):
answer = []
A = [Trie() for _ in range(10001)]
B = [Trie() for _ in range(10001)]
for word in words:
A[len(word)].insert_string(word)
B[len(word)].insert_string(word[::-1])
for query in queries:
flag = query[0] != '?'
string = query if flag else query[::-1]
prefix = string[:string.index('?')]
answer.append(A[len(string)].search(prefix) if flag else B[len(string)].search(prefix))
return answer
print(solution(["frodo", "frond", "frost", "frozen", "frame", "kakao"], ["fro??", "?????"]))
|
e461619064c1baef78415057db2e4f7310c5efb1 | danwspark/CDClabcode | /Queues.py | 4,727 | 3.953125 | 4 | ########################################
# CS63: Artificial Intelligence, Lab 1
# Spring 2016, Swarthmore College
########################################
class _Queue(object):
"""Abstract base class for FIFO_Queue, LIFO_QUEUE, and Random_Queue
A queue supports the following operations:
- adding items with add()
- removing and returning items with get()
- determining the number of items with len()
- checking containment with 'in'
- printing
Child classes are required to store items in the self.contents field, but
may use different data structures for self.contents. Child classes
importantly differ in which item is returned by get().
"""
def __init__(self):
self.contents = []
def add(self, item):
"""Stores item in the queue."""
self.contents.append(item)
def get(self):
"""Removes some item from the queue and returns it."""
raise NotImplementedError("TODO???")
def __len__(self):
""" 'len(q)' calls this method. Passes the len() call to
self.contents. This requires that all child classes implement
contents as a Python type with a valid __len__.
"""
return len(self.contents)
def __repr__(self):
""" 'print q' calls this method. Passes the repr() call to
self.contents. This requires that all child classes implement
contents as a Python type with a valid __repr__.
"""
return repr(self.contents)
def __contains__(self, item):
""" x in q' calls this method.
Passes the containment check to self.contents. This requires that all
child classes implement contents as a Python type with a valid
__contains__.
"""
return item in self.contents
class QueueException(Exception):
def __init__(self, msg):
self.message = msg
class FIFO_Queue(_Queue):
"""First-in-first-out, also known as a classic 'queue', queue
implementation. The first call to get() returns the item from the
first call to add(), the second returns the second, and so on.
"""
def get(self):
try:
return self.contents.pop(0)
except IndexError:
raise QueueException("Can't get from an empty queue")
class LIFO_Queue(_Queue):
"""Last-in-first-out, also known as a 'stack', queue implementation.
The first call to get() returns the item from the most recent call
to add(), the second returns the next-most-recent, and so on.
"""
def get(self):
try:
return self.contents.pop(-1)
except IndexError:
raise QueueException("Can't get from an empty queue")
class Random_Queue(_Queue):
"""Randomized queue implementation. Each call to get() returns an
item from the queue chosen uniformly at random.
"""
def get(self):
if len(self.contents) == 0:
raise QueueException("Can't get from an empty queue")
else:
return self.contents.pop(randrange(len(self.contents)))
from heapq import heappush, heappop
class Priority_Queue(_Queue):
def __init__(self):
self.pq = []
self.contents = set()
def add(self, item, priority):
heappush(self.pq, (priority, item))
self.contents.add(item)
def get(self):
try:
item = heappop(self.pq)[1]
self.contents.remove(item)
except IndexError:
raise QueueException("Can't get from an empty queue")
return item
def __repr__(self):
return repr(self.pq)
def TestPriorityQueue():
print "------------"
print "Testing a PriorityQueue"
pq = PriorityQueue()
print "Check that an empty queue is printable"
print pq
print "Inserting a:10, b:5, c:2, d:12, e:2, f:25, and g:2"
pq.add("a", 10)
pq.add("b", 5)
pq.add("c", 2)
pq.add("d", 12)
pq.add("e", 2)
pq.add("f", 25)
pq.add("g", 2)
print pq
print "Removing the minimum until empty"
while (len(pq)>0):
print pq.get()
def TestQueue(q):
print "------------"
print "Testing", type(q)
for i in range(10):
q.add(i*10)
print "Queue contains:", q
print "Length of Queue is", len(q)
if 22 in q:
print "We have a problem"
if 50 in q:
print "50 is in Queue"
for i in range(10):
print "Get returned", q.get()
try:
q.get()
except QueueException:
print "Correctly throws exception when get called on empty queue"
def main():
TestQueue(FIFO_Queue())
TestQueue(LIFO_Queue())
TestQueue(Random_Queue())
TestPriorityQueue()
if __name__ == '__main__':
main()
|
c0633c04c4d4a4b41dcbeccfabce2f0519724fa2 | 63070086/Pyhon | /21.2D Distance.py | 316 | 3.6875 | 4 | """def"""
def numsum():
"""docstring input"""
numx1 = float(input())
numy1 = float(input())
numx2 = float(input())
numy2 = float(input())
sum1 = (numx2-numx1)**2
sum2 = (numy2-numy1)**2
sum3 = sum1+sum2
sum4 = sum3**0.5
print("Distance = %0.03f"%(sum4))
numsum()
|
46e11ec8a1465890010c9c713677fcdf921c5a21 | 63070086/Pyhon | /22Hexagonal Prism.py | 260 | 3.59375 | 4 | """Describe"""
def sumsum():
""" input"""
rong = float(input())
height = float(input())
square = (rong*height)*6
sum1 = (((((3**0.5)/4)*rong**2)*6)*2)
sum2 = ((square+sum1)/10000)
print("%0.02f squaremetre"%sum2)
sumsum()
|
12ea9a0481d9fbf063445061ff41d822d55673d1 | 63070086/Pyhon | /28Caplock crisis.py | 143 | 3.515625 | 4 | """abc"""
def abc():
"""Lower Translate"""
upper = input()
uplow = ord(upper)
low = uplow+32
print(chr(low))
abc()
|
866b452a25cf61d858f06885874e58a36de6f603 | 63070086/Pyhon | /9Escape Sequence II.py | 398 | 3.6875 | 4 | """input name"""
def numbername():
"""input"""
name1 = input()
name2 = input()
name3 = input()
name4 = input()
name5 = input()
name6 = input()
name7 = input()
name8 = input()
name9 = input()
print("%s\t%s\t%s"%(name1, name2, name3))
print("%s\t%s\t%s"%(name4, name5, name6))
print("%s\t%s\t%s"%(name7, name8, name9))
numbername()
|
076aaca238675218bbd2c8c9458d3d0368865934 | 63070086/Pyhon | /24how long.py | 173 | 3.65625 | 4 | """tran"""
def tran():
"""input int"""
num = int(input())
numabs = abs(num)
num1 = str(numabs)
num3 = len(num1)
print("%d"%(num3))
tran()
|
3dc997bdf2f3bf1628e164c8061ab3da003f7575 | 63070086/Pyhon | /46binary number2.py | 186 | 3.578125 | 4 | """string"""
def main():
"""input func"""
bi_num1 = int(input(), 2)
bi_num2 = int(input(), 2)
bi_num3 = int(input(), 2)
print(bi_num1*bi_num2*bi_num3)
main()
|
3c080adc19961c9138b7604b89503fee237b88d8 | 63070086/Pyhon | /60should be chosen.py | 1,215 | 3.640625 | 4 | """funtion"""
def suba(num):
"""funtion"""
if num >= 1 and num < 4:
num2 = num * 725
return num2
elif num >= 4 and num % 4 == 0:
num1 = num/4
num1 = round(num1)
num2 = (num1*(725*3))
return num2
elif num >= 4 and num % 4 != 0:
num1 = num // 4
excess = num - (num1*4)
num1 = round(num1)
num2 = (num1*(725*3))+(excess*725)
return num2
def subb(num):
"""funtion"""
num3 = num * 549
return num3
def subc(num):
"""funtion"""
num4 = num * 699
if num4 >= 3000:
numper = (num4*20)/100
numper = round(numper)
num4 = num4 - numper
return num4
else:
return num4
def main():
"""input"""
num = abs(int(input()))
if subb(num) > suba(num) > subc(num):
print("A")
elif suba(num) > subb(num) > subc(num):
print("B")
elif suba(num) > subc(num) > subb(num):
print("C")
elif subc(num) > suba(num) > subb(num):
print("A")
elif subc(num) > subb(num) > suba(num):
print("B")
elif subb(num) > subc(num) > suba(num):
print("C")
main()
|
98f50aea08160eed4430d8490e73338b8009620c | justin-ht-dang/competitiveProg | /ICPCprep/ANZACbeginner/arithmetic.py | 346 | 3.90625 | 4 | two_num =input()
num_pair = two_num.split()
num1 = int(num_pair[0])
num2 = int(num_pair[1])
print(str(num1) + " * " + str(num2) + " = " + str(num1*num2))
if(num2 != 0):
print(str(num1) + " / " + str(num2) + " = " + str(num1//num2) + " remainder " + str(num1%num2))
else:
print(str(num1) + " / " + str(num2) + " is an ILLEGAL OPERATION")
|
4d787bf1a4ee7d96216520ffa9331a8a1ad670a0 | nickconway/connect-four | /imports.py | 5,995 | 4.1875 | 4 | import random
# Player marks
BLANK = "_"
PLAYER1 = "X"
PLAYER2 = "O"
# Column constants
MIN_VALUE = 5
MIN_COLUMN = 1
# Input constants
NO = "n"
YES = "y"
# prints out the current board
# Input: board
# Output: None
def printBoard(board):
for row in board:
row_ = 0
count = 0
for col in row:
if count < len(board[row_]) - 1:
print(col, end=" ")
else:
print(col)
count += 1
row_ += 1
# creates the initial unfilled board with the specified width and height
# Input: None
# Output: blank board with a width and height the user specified, the max
# number of turns
def makeBoard():
board = []
height = 0
while height < MIN_VALUE:
height = int(input("How many rows will the board have? "))
if(height < MIN_VALUE):
print("Rows must be greater than 5!")
width = 0
while width < MIN_VALUE:
width = int(input("How many columns will the board have? "))
if(width < MIN_VALUE):
print("Columns must be greater than 5!")
row = []
for count in range(width):
row.append("_")
for count in range(height):
board.append(row[:])
maxTurns = width * height
printBoard(board)
return board, maxTurns
# asks the user if player 2 is ai or human
# Input: None
# Output: if player 2 is a computer (true or false)
def isComputer():
# Get the answer from the player and validate
answer = input("Is player 2 a computer (y or n)? ")
while(answer != NO and answer != YES):
print("Must enter y or n!")
answer = input("Is player 2 a computer (y or n)? ")
return True if answer == "y" else False
# gets the players move and updates the board put piece in, update the board
# Input: the board, the player mark
# Output: the new board, the place where the piece went
def makeMove(board, player):
# Check if the column is full
validMove = False
while(not validMove):
playerNum = 1 if player == PLAYER1 else 2
rowFilled = False
row = -1
col = int(input(f"Player {playerNum}'s turn. What column do you want " +
f"to place your piece in (1 - {len(board[0])})? ")) - 1
while(col < 0 or col >= len(board[0])):
print()
print("Invalid column. Try again!")
print()
col = int(input(f"Player {playerNum}'s turn. What column do you " +
f"want to place your piece in (1 - " +
f"{len(board[0])})? ")) - 1
print()
while(not rowFilled):
if(row < -(len(board))):
print("That column is full! Try again.")
rowFilled = True
validMove = False
elif(board[row][col] == BLANK):
board[row][col] = player
rowFilled = True
validMove = True
row -= 1
row += 1
printBoard(board)
return board, row, col
# the computer first checks if there are any winning moves, then it checks if
# it can block player 1 at all, it then checks if it can place a piece next to
# an existing piece, and lastly, it places its piece in a random column if none
# of the above can be done
# Input: the board
# Output: new board
def makeCompMove(board):
# Check if the column is full
validMove = False
while(not validMove):
rowFilled = False
row = -1
col = random.randint(1, len(board) - 1)
while(not rowFilled):
if(row < -(len(board))):
rowFilled = True
validMove = False
elif(board[row][col] == BLANK):
board[row][col] = PLAYER2
rowFilled = True
validMove = True
row -= 1
row += 1
printBoard(board)
print(f"Computer placed a piece in column {col + 1}.")
return board, row, col
# checks if there is a winner
# Input: board, where the last piece was placed
# Output: the winning player, or False if there is no winner
def isWinner(board, row, col):
rowList = board[row]
colList = []
diagUpRow = []
diagDownRow = []
# Create list to check for vertical row
for row_ in board:
colList.append(row_[col])
# Create lists to check for diagonal rows
for index in range(-3, 4):
rowToCheck = row + index
colToCheck = col - index
if(rowToCheck > -len(board) and \
colToCheck < len(colList) and colToCheck > 0):
diagUpRow.append(board[rowToCheck][colToCheck-1])
rowToCheck = row + index
colToCheck = col + index
if(rowToCheck > -len(board) and \
colToCheck < len(colList) and colToCheck > 0):
diagDownRow.append(board[rowToCheck][colToCheck-1])
# Horizontal 4 in a row
for index in range(len(rowList) - 3):
if(rowList[index] == rowList[index + 1] ==
rowList[index + 2] == rowList[index + 3] != BLANK):
return 1 if rowList[index] == PLAYER1 else 2
# Vertical 4 in a row
if(colList[row] == colList[row + 1] ==
colList[row + 2] == colList[row + 3] != BLANK):
return 1 if colList[row] == PLAYER1 else 2
# Digonal 4 in a row
for index in range(len(diagUpRow) - 3):
if(diagUpRow[index] == diagUpRow[index + 1] ==
diagUpRow[index + 2] == diagUpRow[index + 3] != BLANK):
return 1 if diagUpRow[index] == PLAYER1 else 2
for index in range(len(diagDownRow) - 3):
if(diagDownRow[index] == diagDownRow[index + 1] ==
diagDownRow[index + 2] == diagDownRow[index + 3] != BLANK):
return 1 if diagDownRow[index] == PLAYER1 else 2
# checks if the board is completely full
# Input: the number of turns that have been made, the maximum number of turns
# Output: true or false
def fullBoard(turn, maxTurn):
return True if turn == maxTurn else False |
1f2a54b15cf94c8e841df8de7d9f7b2ec53bbaca | oxygenum44/zpi | /naming.py | 6,879 | 3.59375 | 4 | import operator
import features
import copy
import tweet_cleaner
def assign_names(cleaned_tweets_clusters, method="two_most_frequent"):
"""
Function assigning names to clusters by a given method
:param cleaned_tweets_clusters: List of tweets` clusters (list of lists of lists of words)
:param method: Name of name-assigning method
:return: List of names of clusters
"""
if method == "word_one_most_frequent":
return assign_name_by_most_frequent(cleaned_tweets_clusters, 1)
elif method == "word_two_most_frequent":
return assign_name_by_most_frequent(cleaned_tweets_clusters, 2)
elif method == "word_three_most_frequent":
return assign_name_by_most_frequent(cleaned_tweets_clusters, 3)
elif method == "word_one_tf_idf":
return assign_name_by_tf_idf(cleaned_tweets_clusters, 1)
elif method == "word_two_tf_idf":
return assign_name_by_tf_idf(cleaned_tweets_clusters, 2)
elif method == "word_three_tf_idf":
return assign_name_by_tf_idf(cleaned_tweets_clusters, 3)
def assign_name_by_most_frequent(cleaned_tweets_clusters, amount_of_words):
"""
Function assigning names to clusters by the most frequent words in the cluster
:param cleaned_tweets_clusters: List of tweets` clusters (list of lists of lists of words)
:param amount_of_words: Amount of words in clusters` names
:return: List of names of clusters
"""
names = []
for cluster in cleaned_tweets_clusters:
words_in_cluster = []
for tweet in cluster:
for word in tweet:
words_in_cluster.append(word)
if amount_of_words == 1:
names.append(most_frequent(words_in_cluster))
elif amount_of_words == 2:
first_word = most_frequent(words_in_cluster)
new_list = remove_all(words_in_cluster, first_word)
if len(new_list) > 0:
second_word = most_frequent(new_list)
names.append(first_word + "&" + second_word)
else:
names.append(first_word)
elif amount_of_words == 3:
first_word = most_frequent(words_in_cluster)
new_list = remove_all(words_in_cluster, first_word)
if len(new_list) > 0:
second_word = most_frequent(new_list)
new_list = remove_all(new_list, second_word)
if len(new_list) > 0:
third_word = most_frequent(new_list)
names.append(first_word + "&" + second_word + "&" + third_word)
else:
names.append(first_word + "&" + second_word)
else:
names.append(first_word)
return names
def assign_name_by_tf_idf(cleaned_tweets_clusters, amount_of_words):
"""
Function assigning names to clusters by the most frequent words in the cluster
with frequency of these words in all the tweets` words taken into account
:param cleaned_tweets_clusters: List of tweets` clusters (list of lists of lists of words)
:param amount_of_words: Amount of words in clusters` names
:return: List of names of clusters
"""
all_tweets = []
names = []
for cluster in cleaned_tweets_clusters:
words_in_cluster = []
for tweet in cluster:
for word in tweet:
words_in_cluster.append(word)
all_tweets.append(tweet)
all_features_dictionaries = []
for tweet in all_tweets:
features_dictionary = features.calculate_tf_idf(tweet, all_tweets)
all_features_dictionaries.append(features_dictionary)
clusters_features = []
for cluster in cleaned_tweets_clusters:
cluster_features = []
for i in range(len(all_features_dictionaries)):
if all_tweets[i] in cluster:
cluster_features.append(all_features_dictionaries[i])
clusters_features.append(cluster_features)
clusters_strengths_dictionaries = []
for cluster_features in clusters_features:
cluster_strengths_dictionary = dict()
for tweet_dict in cluster_features:
for word in tweet_dict:
if word in cluster_strengths_dictionary:
cluster_strengths_dictionary[word] += tweet_dict[word]
else:
cluster_strengths_dictionary[word] = tweet_dict[word]
clusters_strengths_dictionaries.append(cluster_strengths_dictionary)
for cluster_strengths_dictionary in clusters_strengths_dictionaries:
if amount_of_words == 1:
names.append(max(cluster_strengths_dictionary.items(), key=operator.itemgetter(1))[0])
elif amount_of_words == 2:
first_word = max(cluster_strengths_dictionary.items(), key=operator.itemgetter(1))[0]
new_dictionary = copy.copy(cluster_strengths_dictionary)
del new_dictionary[first_word]
if len(new_dictionary) > 0:
second_word = max(new_dictionary.items(), key=operator.itemgetter(1))[0]
names.append(first_word + "&" + second_word)
else:
names.append(first_word)
elif amount_of_words == 3:
first_word = max(cluster_strengths_dictionary.items(), key=operator.itemgetter(1))[0]
new_dictionary = copy.copy(cluster_strengths_dictionary)
del new_dictionary[first_word]
if len(new_dictionary) > 0:
second_word = max(new_dictionary.items(), key=operator.itemgetter(1))[0]
del new_dictionary[second_word]
if len(new_dictionary) > 0:
third_word = max(new_dictionary.items(), key=operator.itemgetter(1))[0]
names.append(first_word + "&" + second_word + "&" + third_word)
else:
names.append(first_word + "&" + second_word)
else:
names.append(first_word)
return names
def most_frequent(List):
"""
https://www.geeksforgeeks.org/python-find-most-frequent-element-in-a-list/
Function returning the most frequent element of a list
:param List: List of elements
:return: Most frequent element of the list
"""
return max(set(List), key=List.count)
def remove_all(list, n):
"""
https://www.includehelp.com/python/remove-all-occurrences-a-given-element-from-the-list.aspx
Function removing all occurrences a given element from the list
:param list: Primary state if the list
:param n: Element to be removed
:return: The list after the removal
"""
new_list = copy.copy(list)
i = 0 # loop counter
length = len(new_list)
while i < length:
if new_list[i] == n:
new_list.remove(new_list[i])
length = length - 1
continue
i = i + 1
return new_list
|
94116c21a5799d62dee008a79229a30a598386b9 | adevesa/trucopython | /truco/NaipesEspanioles.py | 3,815 | 3.5625 | 4 | ## Naipes Espanioles funciones.
from itertools import product, permutations
import random
''' @@Name: crear_baraja
@@Parm: none
@@Desc: Crea los 50 naipes españoles, 12 de cada palo y los 2 comodines.
Los Naipes estan constituido en una tupla (PALO, NUMERO)
La baraja es una coleccion de Naipes.
[("COPA",5),("BASTO",8)...]
'''
def crear_baraja():
palo = ["BASTO", "ORO", "ESPADA", "COPA"]
numero = range(1,13)
comodines =[("COMODIN",1), ("COMIDIN",2)]
baraja = (list(product(palo,numero)))
baraja = baraja + comodines
return baraja
''' @@Name: mezclar
@@Parm: baraja
@@Desc: Devuelve una nueva baraja con el orden de las cartas cambiadas aleatoriamente
'''
def mezclar(baraja):
i = 0
cantCartas = len(baraja)
ubicacionesRandom = []
while i < cantCartas:
nRandom = random.randint(0, cantCartas - 1)
if nRandom not in ubicacionesRandom:
ubicacionesRandom = ubicacionesRandom + [nRandom]
i = i + 1
barajaNew = []
for ubic in ubicacionesRandom:
barajaNew.append(baraja[ubic])
return barajaNew
''' @@Name: get_n_cards
@@Parm: baraja, N (numero de cartas)
@@Desc: Dado una baraja, devuelve la N cantidad de cartas y destruye esas cartas de la baraja.
'''
def get_n_cards(baraja,N):
i=0
Cartas = []
if len(baraja) < N:
cartasFaltantes = N - len(baraja)
while i < len(baraja):
Cartas.append(baraja[0])
del baraja[0]
i = i + 1
baraja = mezclar(crear_baraja())
print('No hay mas cartas disponibles, barajando....')
return Cartas + get_n_cards(baraja, cartasFaltantes)
else:
while i < N:
Cartas.append(baraja[0])
del baraja[0]
i = i + 1
return Cartas
''' @@Name: restringir_numero
@@Parm: baraja, numero
@@Desc: Dado una baraja, devuelve una baraja sin cartas con ese numero. No aplica para comodines.
'''
def restringir_numero(baraja, numero):
palo = ["BASTO", "ORO", "ESPADA", "COPA"]
restringidos = (list(product(palo,[numero])))
for rest in restringidos:
if(rest in baraja):
del baraja[baraja.index(rest)]
return baraja
''' @@Name: restrigir_palo
@@Parm: baraja, palo
@@Desc: Dado una baraja, devuelve una baraja sin el palo mencionado. No funciona con comodines.
'''
def restringir_palo(baraja, palo):
numero = range(1,13)
restringidos = (list(product([palo],numero)))
for rest in restringidos:
if(rest in baraja):
del baraja[baraja.index(rest)]
return baraja
''' @@Name: restringir_comodines
@@Parm: baraja
@@Desc: Dado una baraja, devuelve una baraja sin comodines.
'''
def restringir_comodines(baraja):
comodines =[("COMODIN",1), ("COMIDIN",2)]
for comodin in comodines:
if(comodin in baraja):
del baraja[baraja.index(comodin)]
return baraja
''' @@Name: empieza_jugador
@@Parm: Jugadores
@@Desc: Dado una cantidad de jugadores, devuelve un string con "JUGADOR N"
indicando quien empieza, siendo N un numero entre 1 y 'Jugadores'.
'''
def empieza_jugador(Jugadores):
turno = random.randint(1,Jugadores)
return "JUGADOR " + str(turno)
''' @@Name: baraja_truco
@@Parm:
@@Desc: Devuelve una baraja especializada para truco.
'''
def baraja_truco():
baraja = crear_baraja()
baraja = mezclar(baraja)
baraja = restringir_numero(baraja,8)
baraja = restringir_numero(baraja,9)
baraja = restringir_comodines(baraja)
return baraja
|
2a5d3eb589bb0c4591382bf90700987406ff372d | julia-ediamond/python | /recap.py | 728 | 4.34375 | 4 | fruits = ["banana", "apple", "cherry"]
print(fruits[-1])
fruits.append("pineapple")
print(fruits)
fruits.pop(0)
print(fruits)
digits = [1, 2, 3]
decimal = [1, 2, 3]
nested = [[1, 2, 3], ["hello"]]
for item in fruits:
print(item)
for item in nested:
print(item)
for i in item:
print(i)
people = [
["Alice", 25, "pink"],
["Bob", 33, "purple"],
["Anne", 18, "red"],
]
vaccination = []
# Pseudo code
# go through the list
# check the age
# if age 20 or older add this prson to vaccination list
for person in people:
# if person[1] >= 20:
# first iteration ["Alice", 25, "pink"] person[0] - 0 because e need name to be added
# vaccination.append(person[0])
print(vaccination)
|
e1a073464ac2c434d9d4c6ea314ab7422beaac06 | julia-ediamond/python | /dictionaries/dict_ex3.py | 468 | 3.53125 | 4 | names = ["Bel", "Elnaz", "Gia", "Izzy", "Joy", "Katie", "Maddie", "Tash", "Nic", "Rachael", "Bec", "Bec", "Tabitha", "Teagen",
"Viv", "Anna", "Catherine", "Catherine", "Debby", "Gab", "Megan", "Michelle", "Nic", "Roxy", "Samara", "Sasha", "Sophie", "Teagen", "Viv"]
#names_dict = {}.fromkeys(names, "unkown")
# print(names)
list_names = list(set(names))
names_dict = {}.fromkeys(list_names, 0)
for name in names:
names_dict[name] += 1
print(names_dict)
|
f53e3e87ff1962e04b4eec9633b780087bdb1482 | julia-ediamond/python | /loops/for_exer.py | 127 | 3.859375 | 4 | # Q2
start_number = int(input("Enter a number: "))
sum_ = 0
for i in range(0, start_number + 1):
sum_ += i
print(sum_)
|
cf652ca875116897caa6431822093f1bd361e6d3 | julia-ediamond/python | /data/process_employee_birthday.py | 472 | 3.609375 | 4 | import csv
with open('data\data1\employee_birthday.csv', mode="r") as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=",")
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
print(
f'\t{row["name"]} works in the {row[" department"]} department, and was born in {row[" birthday month"]}.')
line_count += 1
print(f"Processed {line_count} lines.")
|
d899282f97173cc5aa3af6bba09934a2a43a8a95 | lucpena/Stonks.py | /stonks.py | 3,297 | 3.53125 | 4 | import math
import numpy as np
import pandas as pd
import pandas_datareader as web
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
plt.style.use("fivethirtyeight")
# Getting the DataFrame with the stock quote
df = web.DataReader("NFLX", data_source="yahoo", start="2012-01-03", end="2020-04-01")
# Shows the head and the tail of the DataFrame created
# print(df)
# Shows the number of rows and columns in the data set
# print(df.shape)
# Plots the closing price history
# plt.figure(figsize=(16,8))
# plt.title("Close Price History - Netflix")
# plt.plot(df["Close"])
# plt.xlabel("Date", fontsize=18)
# plt.ylabel("Close Price USD ($)", fontsize=18)
# plt.show()
# A new DataFrame with only the 'Close' column
data = df.filter(["Close"])
# Converting to numpy
dataset = data.values
# Getting the number of rows to train our model, setting the size of our training model to 80%
# and rounding up the values
training_data_len = math.ceil(len(dataset) * 0.8)
# Scaling the data to use in the neural network and help the model
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
# print(scaled_data)
# Crating the Training DataSet and the scaled Training DataSet
train_data = scaled_data[0:training_data_len, :]
# Splitting the data into x_train and y_train data sets
x_train = []
y_train = []
for i in range(60, len(train_data)):
x_train.append(train_data[i-60:i, 0])
y_train.append(train_data[i, 0])
# Converting yo numpy
x_train, y_train = np.array(x_train), np.array(y_train)
# Reshaping the data (from 2D to 3D)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
# Building the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
# Compiling the model
model.compile(optimizer="adam", loss="mean_squared_error")
# Training the model
model.fit(x_train, y_train, batch_size=1, epochs=1)
# Creating the testing DataSet and a new array containing the scaled values
test_data = scaled_data[training_data_len - 60:, :]
# Creating the DataSets x_test and y_test
x_test = []
y_test = dataset[training_data_len:, :]
for i in range(60, len(test_data)):
x_test.append(test_data[i-60:i, 0])
# Convert to numpy
x_test = np.array(x_test)
# Reshape the data
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
# Getting the models predicted price values
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
# Getting the root mean squared error (RMSE)
rmse = np.sqrt(np.mean(((predictions - y_test) ** 2)))
# Plotting the data
train = data[:training_data_len]
valid = data[training_data_len:]
valid["Predictions"] = predictions
plt.figure(figsize=(16, 8))
plt.title("Netflix Close Prices")
plt.xlabel("Date", fontsize=18)
plt.ylabel("Close Prices USD ($)", fontsize=18)
plt.plot(train["Close"])
plt.plot(valid[["Close", "Predictions"]])
plt.legend(["Train", "Val", "Predictions"], loc="lower right")
plt.show()
|
6fe3950c7987a7485c2565c2477d84c677a8eb9c | StevenCThaller/March20PythonAlgos | /validbraces.py | 1,376 | 4.0625 | 4 | from stacks import *
def ValidBraces(string):
# set of opening and closing braces for easy checking
openings = [ "(", "[", "{" ]
closings = [ ")", "]", "}" ]
# dictionary of opening braces and their corresponding closing braces
valids = {
"(": ")",
"{": "}",
"[": "]" }
# creating a stack from the previous day's algo
brace_stack = Stack()
# Iterate through the string
for i in string:
# If a character is an opening brace
if i in openings:
# Push the opening brace into the stack
brace_stack.Push(i)
# Else if the character is a closing brace
elif i in closings:
# Check to see that there is an opening brace in the stack, and then
# Check to see if the closing brace matches the most recent opening brace in the stack
if brace_stack.Peek() != None and i == valids[brace_stack.Peek()]:
# If it matches, remove the opening brace from the top of the stack
brace_stack.Pop()
else:
# If the braces DON'T match, the string is invalid
return False
# Check to see that there are no leftover opening braces left in the stack
if brace_stack.Peek() != None:
return False
else:
return True
print(ValidBraces(")))}")) |
38e477dfea4d52fec96a70aeb69df0d0a32fcf3b | saequus/learn-python-favorites | /Tasks/InterestingStr.py | 684 | 3.734375 | 4 | # https://leetcode.com/discuss/interview-question/350312/google-onsite-interesting-string
from functools import lru_cache
def interesting_string(s):
@lru_cache(maxsize=len(s))
def dfs(i):
if i == len(s):
return True
j = i
while j < len(s) and s[j].isdigit():
k = int(s[i:j + 1])
if dfs(j + k + 1):
return True
j += 1
return False
return dfs(0)
s = "4g12y6hunter"
print(interesting_string(s), True)
s = "124gray6hunter"
print(interesting_string(s), True)
s = "31ba2a"
print(interesting_string(s), False)
s = "3abc4defg3abc4defg3abc"
print(interesting_string(s), True)
|
9cd88a850ddd8efceeff3721b6a39eedef99e9d3 | saequus/learn-python-favorites | /Tasks/24_SwapPairs.py | 6,218 | 3.9375 | 4 | # class Node:
# def __init__(self, val):
# self.val = val
# self.next = None
#
# def traverse(self):
# node = self
# while node:
# print(node.val)
# node = node.next
#
# class SpecialList:
# def __init__(self):
# self.head = Node
#
# def listprint(self):
# printval = self.head
# while printval is not None:
# print(printval.val)
# printval = printval.next
#
# def atBegining(self, data_in):
# newNode = Node(data_in)
# newNode.next = self.head
# self.head = newNode
# l1 = SpecialList()
# l1.head = Node(12)
# node1 = Node(29)
# node2 = Node(34)
# node3 = Node(34)
# node4 = Node(51)
#
# l1.head.next = node1
# node1.next = node2
# node2.next = node3
# node3.next = node4
#
# l1.atBegining(100)
# print(l1.listprint())
# print(node1.next.val)
# print(node1.traverse())
#
#
#
# class Days:
# def __init__(self, val):
# self.val = val
# self.next = None
#
# def traverse(self):
# node = self
# while node:
# print(node.val)
# node = node.next
#
# def addday(self, newdata, b=None):
# newDay = Days(newdata)
#
#
#
# day1 = Days('Monday')
# day2 = Days('Tuesday')
# day3 = Days('Wednesday')
#
# day1.next = day2
# day2.next = day3
#
# print(day1.traverse())
#
# class Node:
# def __init__(self, val):
# self.val = val
# self.next = None
#
# def traverse(self):
# node = self
# while node:
# print(node.val)
# node = node.next
#
#
# class SpecialList:
#
# def __init__(self):
# self.head = Node
#
# def printlist(self):
# node = self.head
# while node:
# print(node.val)
# node = node.next
#
# def addBefore(self, value):
# head = self.head
# newNode = Node(value)
# newNode.next = head
# self.head = newNode
# - - - - - - - - - - - - - - - -
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def traverse(self):
node = self
while node:
print(node.val)
node = node.next
class SpecialList(object):
def __init__(self):
self.head = Node
def printlist(self):
node = self.head
while node:
print(node.val)
node = node.next
def addBefore(self, value):
head = self.head
newNode = Node(value)
newNode.next = head
self.head = newNode
def addAfter(self, val):
node = self.head
newNode = Node(val)
while node:
print(node.val)
if not node.next:
node.next = newNode
break
node = node.next
def addMiddle(self, position, val):
node = self.head
newNode = Node(val)
while node:
if node.val == position:
nextNode = node.next
node.next = newNode
newNode.next = nextNode
break
node = node.next
# def swapPairs(self, head):
# prev = Node(0)
# prev.next = head
# node = prev
# while node.next and node.next.next:
# next_node = node.next
# temp_value = node.val
# temp_next = node.next
# node.val = next_node.val
# next_node.val = temp_value
# print(next_node.val, 'next_node value')
# node.next = next_node.next
# next_node.next = temp_next
# print(next_node.next, 'next_node next')
# node = node.next
def swapPairs(self):
prev = Node(0)
prev.next = self.head
node = prev
while node.next and node.next.next:
first = node.next
second = node.next.next
# change the pointers to the swapped pointers
node.next = second
first.next = second.next
second.next = first
node = node.next.next
self.head = prev.next
def swap(self):
head = self.head
if head is None:
return head
elif head.next is None:
return head
else:
res = head
total = 0
before = head
while head is not None:
if head.next is not None:
temp = head
temp1 = head.next
temp.next = head.next.next
temp1.next = temp
head = head.next
if total == 0:
total += 1
res = temp1
else:
before.next = temp1
before = temp
else:
break
return res
node1 = Node(29)
node2 = Node(31)
node3 = Node(34)
node4 = Node(39)
node1.next = node2
node2.next = node3
node3.next = node4
l1 = SpecialList()
l1.head = node1
print(l1.printlist())
l1.swap()
print(l1.printlist())
# - - - - - - - - - - - - - - - -
#
# # Definition for singly-linked list.
#
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# class Solution:
# def __init__(self):
# self.main = ListNode
#
# # def swapPairs(self, head):
# # node = self.main
# # while node:
# # next_node = node.next
# # temp_value = node.val
# # temp_next = node.next
# # node.val = next_node.val
# # next_node.val = temp_value
# # node.next = next_node.next
# # next_node.next = temp_next
# # node = node.next
#
# def printlist(self):
# node = self.main
# while node:
# print(node.val)
# node = node.next
#
#
# node1 = ListNode(29)
# node2 = ListNode(31)
# node3 = ListNode(34)
# node4 = ListNode(39)
#
# node1.next = node2
# node2.next = node3
# node3.next = node4
#
#
# l2 = Solution()
# l2.head = node1
# # l2.swapPairs(node1)
# print(l2.printlist())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.