blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
add8cfc152244945ade97744288fcc4918b1ff68 | SvVoRPy/coursera | /python3_specialization/course04_classes_and_inheritances/week02.py | 11,607 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 12 11:19:52 2020
@author: svollnhals
Python 3 Specialization on Coursera
Course 4 Python Classes and Inheritance
Week 02 stuff
"""
# 22.2 Inheriting Variables and Methods
import time
CURRENT_YEAR = int(time.strftime("%Y"))
class Person:
def __init__(self, name, year_born):
self.name = name
self.year_born = year_born
def getAge(self):
return CURRENT_YEAR - self.year_born
def __str__(self):
return '{} ({})'.format(self.name, self.getAge())
alice = Person('Alice Smith', 1990)
print(alice)
# modified to a studen class with another knowledge instance
class Student:
def __init__(self, name, year_born):
self.name = name
self.year_born = year_born
self.knowledge = 0
def study(self):
self.knowledge += 1
def getAge(self):
return CURRENT_YEAR - self.year_born
def __str__(self):
return '{} ({})'.format(self.name, self.getAge())
alice = Student('Alice Smith', 1990)
print(alice)
print(alice.knowledge)
# Easier with inheritance!!!
# -> conceptual: Every student is a person and can be inheritad from Person
class Student(Person):
def __init__(self, name, year_born):
# call the instructor from the Person class
Person.__init__(self, name, year_born)
self.knowledge = 0
def study(self):
self.knowledge += 1
alice = Student('Alice Smith', 1990)
alice.study()
print(alice.knowledge)
print(alice) # -. able to call getAge and __str__ via Person in Student!
### Overriding Methods
# general: a sub-class gets inherited from a super-class, instance gets created
# of sub-class
# Ordering to search for called method:
# 1) look in instance
# 2) look in sub-class (class of instance)
# 3) look in super-class of sub-class
# When should you inherit? Only(!) if sub-class has everything that also
# super-class has plus something more or modified
class Book():
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return '"{}" by {}'.format(self.title, self.author)
myBook = Book('The Odyssey', 'Homer')
print(myBook)
# now: paper and e-books as sub classes of a book
class PaperBook(Book):
def __init__(self, title, author, numPages):
Book.__init__(self, title, author)
self.numPages = numPages
class EBook(Book):
def __init__(self, title, author, size):
Book.__init__(self, title, author)
self.size = size
myEBook = EBook('The Odyssey', 'Homer', 2)
myPaperBook = PaperBook('The Odyssey', 'Homer', 500)
print(myEBook.size)
print(myPaperBook.numPages)
# -> EBook and PaperBook have everthing that super-class has, plus one more
# characteristic (size or numPages)
### When you don't want to inherit!
# library that contains books
class Library:
def __init__(self):
self.books = []
def addBook(self, book):
self.books.append(book)
def getNumBooks(self):
return len(self.books)
aadl = Library()
myEBook = EBook('The Odyssey', 'Homer', 2)
myPaperBook = PaperBook('The Odyssey', 'Homer', 500)
aadl.addBook(myEBook)
aadl.addBook(myPaperBook)
print(aadl.getNumBooks())
# -> library is not a super-class for the books, as it has different charact.
### Invoking the Parent Class Method
from random import randrange
# Here's the original Pet class, which involves a method feed
# every Pet has its own way to say thank you if you feed him...
# so the method has to be overwritten for every Pet class (see below)
class Pet():
boredom_decrement = 4
hunger_decrement = 6
boredom_threshold = 5
hunger_threshold = 10
sounds = ['Mrrp']
def __init__(self, name = "Kitty"):
self.name = name
self.hunger = randrange(self.hunger_threshold)
self.boredom = randrange(self.boredom_threshold)
self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class
def clock_tick(self):
self.boredom += 1
self.hunger += 1
def mood(self):
if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold:
return "happy"
elif self.hunger > self.hunger_threshold:
return "hungry"
else:
return "bored"
def __str__(self):
state = " I'm " + self.name + ". "
state += " I feel " + self.mood() + ". "
# state += "Hunger %d Boredom %d Words %s" % (self.hunger, self.boredom, self.sounds)
return state
def hi(self):
print(self.sounds[randrange(len(self.sounds))])
self.reduce_boredom()
def teach(self, word):
self.sounds.append(word)
self.reduce_boredom()
def feed(self):
self.reduce_hunger()
def reduce_hunger(self):
self.hunger = max(0, self.hunger - self.hunger_decrement)
def reduce_boredom(self):
self.boredom = max(0, self.boredom - self.boredom_decrement)
# Dog is a sub-class of Pet that modifies the feed
class Dog(Pet):
def feed(self):
print('Arf! Thanks')
# call feed from super-class!
Pet.feed(self)
d1 = Dog('YoYoBelly')
d1.feed()
class Bird(Pet):
sounds = ["chirp"]
def __init__(self, name = "Kitty", chirp_number = 2):
Pet.__init__(self, name) # call the parent class's constructor
# basically, call the SUPER -- the parent version -- of the constructor
# with all the parameters it needs.
self.chirp_number = chirp_number
def hi(self):
for i in range(self.chirp_number):
print(self.sounds[randrange(len(self.sounds))])
self.reduce_boredom()
b1 = Bird('tweety', 5)
b1.teach("Polly wanna cracker")
b1.hi()
print(b1)
#####################################################################
### Assignments Week 02
class Pokemon(object):
attack = 12
defense = 10
health = 15
p_type = "Normal"
def __init__(self, name, level = 5):
self.name = name
self.level = level
def train(self):
self.update()
self.attack_up()
self.defense_up()
self.health_up()
self.level = self.level + 1
if self.level%self.evolve == 0:
return self.level, "Evolved!"
else:
return self.level
def attack_up(self):
self.attack = self.attack + self.attack_boost
return self.attack
def defense_up(self):
self.defense = self.defense + self.defense_boost
return self.defense
def health_up(self):
self.health = self.health + self.health_boost
return self.health
def update(self):
self.health_boost = 5
self.attack_boost = 3
self.defense_boost = 2
self.evolve = 10
def __str__(self):
self.update()
return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level)
class Grass_Pokemon(Pokemon):
attack = 15
defense = 14
health = 12
def update(self):
self.health_boost = 6
self.attack_boost = 2
self.defense_boost = 3
self.evolve = 12
def moves(self):
self.p_moves = ["razor leaf", "synthesis", "petal dance"]
def action(self):
return '{} knows a lot of different moves!'.format(self.name)
p1 = Grass_Pokemon('Belle')
print(p1)
# Modify the Grass_Pokemon subclass so that the attack strength for
# Grass_Pokemon instances does not change until they reach level 10.
# At level 10 and up, their attack strength should increase by the
# attack_boost amount when they are trained.
# To test, create an instance of the class with the name as "Bulby".
# Assign the instance to the variable p2. Create another instance of the
# Grass_Pokemon class with the name set to "Pika" and assign that instance to
# the variable p3. Then, use Grass_Pokemon methods to train the p3
# Grass_Pokemon instance until it reaches at least level 10.
class Grass_Pokemon(Pokemon):
attack = 15
defense = 14
health = 12
p_type = "Grass"
# only update attack by boost after level 10
def update(self):
self.health_boost = 6
# gets level from super class Pokemon, as not existent in Grass_Pokemon
if self.level >= 10:
self.attack_boost = 2
else:
self.attack_boost = 0
self.defense_boost = 3
self.evolve = 12
def moves(self):
self.p_moves = ["razor leaf", "synthesis", "petal dance"]
p2 = Grass_Pokemon('Bulby')
p3 = Grass_Pokemon('Pika')
print(p2); print(p3)
# train Pika x times
n_trains = 10
for i in range(n_trains):
attack_before = p3.attack
p3.train()
print('Trained {} to level {}, attack was at {}, is now at {}'
.format(p3.name, p3.level, attack_before, p3.attack))
# Along with the Pokemon parent class, we have also provided several subclasses
# Write another method in the parent class that will be inherited by the
# subclasses. Call it opponent. It should return which type of pokemon the
#current type is weak and strong against, as a tuple.
# Grass is weak against Fire and strong against Water
# Ghost is weak against Dark and strong against Psychic
# Fire is weak against Water and strong against Grass
# Flying is weak against Electric and strong against Fighting
# For example, if the p_type of the subclass is 'Grass', .opponent() should
# return the tuple ('Fire', 'Water')
class Pokemon():
attack = 12
defense = 10
health = 15
p_type = "Normal"
def __init__(self, name,level = 5):
self.name = name
self.level = level
self.weak = "Normal"
self.strong = "Normal"
def train(self):
self.update()
self.attack_up()
self.defense_up()
self.health_up()
self.level = self.level + 1
if self.level%self.evolve == 0:
return self.level, "Evolved!"
else:
return self.level
def attack_up(self):
self.attack = self.attack + self.attack_boost
return self.attack
def defense_up(self):
self.defense = self.defense + self.defense_boost
return self.defense
def health_up(self):
self.health = self.health + self.health_boost
return self.health
def update(self):
self.health_boost = 5
self.attack_boost = 3
self.defense_boost = 2
self.evolve = 10
def opponent(self):
self.map = {'Grass': ('Fire', 'Water'), 'Ghost': ('Dark', 'Psychic'),
'Fire': ('Water', 'Grass'), 'Flying': ('Electric', 'Fighting')}
return self.map[self.p_type]
def __str__(self):
self.update()
return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level)
class Grass_Pokemon(Pokemon):
attack = 15
defense = 14
health = 12
p_type = "Grass"
def update(self):
self.health_boost = 6
self.attack_boost = 2
self.defense_boost = 3
self.evolve = 12
class Ghost_Pokemon(Pokemon):
p_type = "Ghost"
def update(self):
self.health_boost = 3
self.attack_boost = 4
self.defense_boost = 3
class Fire_Pokemon(Pokemon):
p_type = "Fire"
class Flying_Pokemon(Pokemon):
p_type = "Flying"
Flying_Pokemon('TestPokemon').opponent()
|
d5b64d247b3547f94ce8c5b02c155539c8f4980f | mylove1/demo | /xzs_data/datamigration/mo2my/test.py | 427 | 3.59375 | 4 | class hello():
def __init__(self):
self.a = {
"b": [2, 3, ]
}
def hello(self, sd):
self.a["b"].append(sd)
print self.a
def hel():
for x in range(20):
yield x
def addadd(x):
x += 1
maping = {
'a': 'A',
'b': 'B',
'c': 'C',
}
column = ['b', 'c', 'a']
dic = {
'A': '1',
'B': '2',
'C': '3',
}
print [dic[maping[x]] for x in column] |
3d19cd5b83c0ac6ed7f5bd1c8a345dd77ab71026 | HyunminHong/linear-regression | /src/OLS.py | 4,629 | 3.9375 | 4 | from src.LinearModel import LinearModel
import numpy as np
import matplotlib.pyplot as plt
class OLS(LinearModel):
"""
X: an exogenous variable is one whose value is determined outside the model and is imposed on the model
y: an endogenous variable is a variable whose value is determined by the model
"""
def __init__(self, X = None, y = None, intercept = True):
super().__init__(X = None, y = None, intercept = True)
self.rank = None # rank of the design matrix X
self._dof_model = None # model degrees of freedom
self._dof_resid = None # residual degrees of freedom
self.beta = None # regression coefficients
# TODO if X is a vector, then X.shape[1] does not exist.
self.nob = None # number of observations
self.y_pred = None # predicted value of y based on OLS estimate
self.r_squared = None
self.r_squared_adj = None
def fit(self, X, y, method = "qr"):
"""
Through the QR-decomposition of the X matrix, we can compute the least-squares coefficients.
X = Q * R where Q is an orthogonal matrix and R is an upper triangular matrix.
We solve for beta:
X.T * X * beta = X.T * y
Then, the LHS can be written as:
R.T * (Q.T * Q) * R = R.T * R due to the orthogonality.
Hence, we then have:
R.T * R * beta = R.T * Q.T * y => R * beta = Q.T * y
"""
if self.X == None:
self.X = X
if self.y == None:
self.y = y
self.nob = X.shape[0]
self.rank_exog()
self.dof_model()
self.dof_resid()
try: # X.T * X is a matrix
if method == "qr":
Q, R = np.linalg.qr(self.X)
self.beta = np.linalg.solve(R, np.dot(Q.T, self.y))
elif method == "conv":
"""
conventional way of computing beta:
beta = (X.T * X)^(-1) * X.T * y
"""
self.beta = np.linalg.solve(np.dot(self.X.T, self.X), np.dot(self.X.T, self.y))
return self
except np.linalg.LinAlgError: # X.T * X is a constant, i.e., X is a nx1 vector
self.beta = np.divide(np.dot(self.X.T, self.y), np.dot(self.X.T, self.X))
return self
def predict(self, X_test):
"""
y_pred = _X*beta where beta is the OLS estimate
example.
y = a + b*X1 + c*X2 = X * beta where X = [1 X2 X3] and beta = [a b c].T
y_pred = X_test * beta
"""
self.y_pred = np.dot(X_test, self.beta)
return self.y_pred
def rss_calc(self):
"""
residual sum of errors (RSS). (it is equivalent to SSR in Hayashi)
resid.T * resid
"""
resid = self.y - np.dot(self.X, self.beta)
self.rss = np.dot(resid, resid)
def tss_calc(self):
"""
total sum of squares (TSS).
(y - mean(y)).T * (y - mean(y))
if it has no intercept, no need to center, i.e,. y.T * y
"""
if self.intercept:
y_centered = self.y - np.mean(self.y)
self.tss = np.dot(y_centered, y_centered)
else:
self.tss = np.dot(self.y, self.y)
def ess_calc(self):
"""
explained sum of squares (ESS).
(y_pred - mean(y)).T * (y_pred - mean(y))
if it has no intercept, no need to center, i.e,. y_pred.T * y_pred
"""
self.rss_calc()
self.tss_calc()
self.ess = self.tss - self.rss
def rsquared(self):
"""
Note that:
* TSS = ESS + RSS
* Rsquared = 1 - RSS/TSS
"""
self.rss_calc()
self.tss_calc()
if self.r_squared == None:
self.r_squared = 1 - np.divide(self.rss, self.tss)
return self.r_squared
#TODO
def rsquared_adj(self):
"""
adjusted Rsquared = 1 - (1 - Rsquared)*(N - 1)/(N - p - 1)
if no intercept is given, then no -1 term in denominator
"""
self.rss_calc()
self.tss_calc()
self.rsquared()
return 1 - ((1 - self.r_squared) * np.divide(self.nob - self.intercept, self._dof_resid))
def plot_regression(self, method = "PCA"):
if method == "PCA":
"""
plot the regression line using PCA (dimension reduction)
TODO can we do PCA without using Scikit learn?
"""
pass
if method == "proj":
"""
plot on projection
"""
pass |
fda05cacfcf4a91b02975306ce8e82967fe2e198 | Kratos-28/258349_Daily_Commit | /Session_3_Solved_question/if-elif-else_Solution/Check_data_type.py | 425 | 4.0625 | 4 | number=input()
if number.isalpha():
print("Type is String.")
elif number=="0":
print("Type is Zero()0.")
elif number.isnumeric():
print("Type is Integer or real number.")
else:
try:
number=float(number)
print("Type is float number.")
except:
try:
number=complex(number)
print("Type is complex number.")
except:
print("Invalid type.") |
98a2e8867abc28d96f66015f47855db89116ea8f | Interloper2448/BCGPortfolio | /Python_Files/murach/exercises/ch06/test_scores.py | 1,501 | 4.0625 | 4 | #!/usr/bin/env python3
def display_welcome():
print("**************************************")
print("The Test Scores program")
print("Enter 'x' to exit")
print("")
def get_scores():
scores = []
score_total = 0
while True:
score = input("Enter test score: ")
if score == "x":
return scores
else:
score = int(score)
if score >= 0 and score <= 100:
scores.append(score)
score_total += score
else:
print("Test score must be from 0 through 100. " +
"Score discarded. Try again.")
def process_scores(scores):
# calculate average score
average = sum(scores) / len(scores)
median = 0
if(len(scores)%2==0):
n1 = scores[int(len(scores)/2-1)]
n2 = scores[int(len(scores)/2)]
median = round((n1 + n2)/2,2)
else:
median = scores[int(len(scores)/2)]
# times
# format and display the result
print()
print("Total:\t\t\t", sum(scores))
print("Number of Scores:\t", len(scores))
print("Average Score:\t\t", average)
print("Low Score:\t\t",min(scores))
print("High Score:\t\t", max(scores))
print("Median Score:\t\t",median)
def main():
display_welcome()
scores = get_scores()
process_scores(scores)
print("")
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
|
9c63b9403d43a4082fd9cc80357042b3f2b9fd9b | Vardominator/SorinLab | /misc/bottomUpHierarchicalClustering.py | 3,217 | 4.0625 | 4 | """
Algorithm for Bottom-up Hierarchical Clustering:
1. Make each input its own cluster of one
2. As long as there are multiple clusters remaining,
find the two closest clusters and merge them.
At the end we'll have one giant cluster containing all the inputs. If we keep
track of the merge order, we can recreate any number of clusters by unmerging.
For example, if we want three clusters, we can just undo the last two mergest.
"""
import numpy as np
import pandas as pd
class BottomUp:
"""
merged cluster will be represented as follows:
merged = [1, [leaf1, leaf2]]
merged = [2, [[leaf1, leaf2], [leaf1, leaf2]]
merged = [3, [[[...]]]]
The first value is the order of the merge. Order 1 means that there is a single cluster.
Order n means that there are n cluster.
The leaves in this case are the cluster points that are merged together.
"""
def isLeaf(cluster):
"""a cluster is a leaf if it has length 1"""
return len(cluster) == 1
def getChildren(cluster):
"""returns the children of this cluster if it's a merged cluster;
raises exception if this is a leaf cluster"""
if isLeaf(cluster):
raise TypeError("a leaf cluster has no children")
else:
return cluster[1]
def getValues(cluster):
"""returns value(s) of the cluster"""
if isLeaf(cluster):
return cluster
else:
# for every child in cluster, retrieve the children
return np.array([[value for value in getValues(child)]
for child in getChildren(cluster)])
def euclidianDist(pointA, pointB):
return np.linalg.norm(pointA - pointB)
def clusterDistance(cluster1, cluster2, distanceAgg=min):
"""compute all pairwise distances between cluster 1 and 2
and apply distanceAgg to the resultng list"""
distances = np.array([[euclidianDist(p1, p2) for p1 in cluster1]
for p2 in cluster2])
return distanceAgg(distances)
def getMergeOrder(cluster):
if isLeaf(cluster):
return float('inf')
else:
return cluster[0]
def bottomUpCluster(inputs, distanceAgg = min):
cluster = np.array[inputs]
# as long as we have more than one cluster left
while len(cluster) > 1:
# find the two closest clusters
c1, c2 = min([(cluster1, cluster2)
[for i, cluster1 in enumerate(clusters)]
for cluster2 in clusters[:i]], key=lambda (x,y): clusterDistance(x, y, distanceAgg))
# remove them from the list of clusters
clusters = np.array([c for c in clusters if c != c1 and c !=c2])
# merge them using mergeOrder
mergedCluster = np.array(len(clusters), [c1, c2])
# and add their merge
clusters = np.array(clusters, mergedCluster)
return clusters[0] |
d61b152a9f53d2ed90ea5d930d84f9275be1bb5b | jeanbond/lintcode | /single-number-iii/single-number-iii.py | 825 | 3.578125 | 4 | class Solution:
'''
Important comment: 2018.08.05 xuwei at home for h3c working;
xor and or not are the most important operation in computer world, filled again;
please add comment at soon;
'''
def singleNumberIII(self, A):
ret = []
a, b, xor, loc = 0, 0, 0, 0
#xor all data;
for i in A:
xor ^= i
#find the first diff location;
for i in range(32):
if (xor>>i)&1 == 1:loc = i
## oper two sets in diffrent way;
for i in A:
ks = (i >> loc)&1
if ks == 1: a ^= i
else:
b ^= i
#add two element into answer;
ret.append(a);ret.append(b)
return ret
if __name__ == "__main__":
#
print(Solution().singleNumberIII([4,12])) |
15e133ecc688936e7b85922cbf3241c7c7f992e3 | parasmaharjan/Python_DeepLearning | /LAB2/Problem2.py | 3,631 | 3.96875 | 4 | # Creating list of contacts
contact_list = []
class Contact:
def __init__(self, name, number, email):
self.name = name
self.number = number
self.email = email
contact_list.append([self, self.name, self.number])
def display_name(self):
return self.name
def display_number(self):
return self.number
def display_email(self):
return self.email
# For update info
def update(self, name, number, email):
self.name = name
self.number = number
self.email = email
def display_all():
print('')
print('Name\tNumber\t\t\tEmail')
print('---------------------------------')
for contact in contact_list:
print(contact[0].display_name(), '\t', contact[0].display_number(), '\t', contact[0].display_email())
print('')
def display_by_name(search_name):
for contact in contact_list:
# print(contact)
if contact[1] == search_name:
print('')
print('Name: ', contact[0].display_name())
print('Number: ', contact[0].display_number())
print('Email: ', contact[0].display_email())
break
def display_by_number(search_number):
for contact in contact_list:
# print(contact)
if contact[2] == search_number:
print('')
print('Name: ', contact[0].display_name())
print('Number: ', contact[0].display_number())
print('Email: ', contact[0].display_email())
break
def edit_by_name(old_name, new_name, new_number, new_email):
# Check if name or contact already exist
for contact in contact_list:
if (new_name in contact) | (new_number in contact):
print('')
print("Name or Number already exist")
break
# Find the index of the old name and replace it with the new info
for idx, contact in enumerate(contact_list):
if contact[1] == old_name:
contact[0].update(new_name, new_number, new_email)
contact_list[idx][1] = new_name
contact_list[idx][2] = new_number
display_all()
def main():
# Creating the instance of class Contact
contact_1 = Contact('Paras', '9849xxxxxx', 'paras.maharjan@gmail.com')
contact_2 = Contact('Sushma', '9860xxxxxx', 'sushma.maharjan@gmail.com')
contact_3 = Contact('Sarap', '9861xxxxxx', 'sarap.maharjan@gmail.com')
while True:
print('')
print('0. Display all contact list')
print('1. Display contact by name')
print('2. Display contact by number')
print('3. Edit contact by name')
print('4. Exit\n\r')
option = input("Select any of the above: ")
print('')
if option == '0':
display_all()
elif option == '1':
name = input('Search name: ')
display_by_name(name)
elif option == '2':
number = input('Search number: ')
display_by_number(number)
elif option == '3':
old_name = input('Enter old name: ')
new_name = input('Enter new name: ')
new_number = input('Enter new number: ')
new_email = input('Enter new email: ')
print('')
edit_by_name(old_name, new_name,new_number, new_email)
else:
exit()
def test():
contact_1 = Contact('Paras', '9849xxxxxx', 'paras.maharjan@gmail.com')
contact_2 = Contact('Sushma', '9860xxxxxx', 'sushma.maharjan@gmail.com')
display_by_name('Paras')
edit_by_name('Paras', 'Sarap', '9861xxxxxx', 'sarap.maharjan@gmail.com')
display_by_number('9860xxxxxx')
if __name__ == "__main__":
main()
#test()
|
30e3c3ef0c2dd36005e55420ab8476f1b2034f81 | arhankundu99/GUI-Apps | /Pygame/Sorting Algorithms/bubble sort.py | 1,743 | 3.53125 | 4 | import pygame
import random
pygame.init()
arr = []
x = 40
y = 40
width = 20
screen = pygame.display.set_mode((700, 700))
screen.fill((255, 255, 255))
font = pygame.font.SysFont("comicsans", 40)
def reset_arr():
for i in range(0, 20):
arr.append(100*(random.random()+0.05))
def show_arr():
for i in range(0, 20):
pygame.draw.rect(screen, (255, 0, 0), (x + 30 * i, y, width, arr[i]*5))
update_display()
def update_display():
pygame.display.update()
def show_initial_text():
text = font.render("Press enter to start", 1, (0, 0, 0))
screen.blit(text, (220, 570))
update_display()
def swap(i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def bubble_sort():
for i in range(len(arr)-1, 0, -1):
for j in range(0, i):
if arr[j] > arr[j+1]:
swap(j, j+1)
screen.fill((255, 255, 255))
show_arr()
pygame.time.wait(50)
print(arr)
def show_reset_text():
text = font.render("Press R to reset", 1, (0, 0, 0))
screen.blit(text, (220, 570))
update_display()
reset_arr()
show_initial_text()
show_arr()
update_display()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
bubble_sort()
show_reset_text()
if event.key == pygame.K_r:
arr = []
screen.fill((255, 255, 255))
reset_arr()
show_initial_text()
show_arr()
update_display()
|
b961171611c5149195bb800f363340ad4b67613b | sureshlodha/Indian-Population-Density | /2011/Data/data-state.py | 961 | 3.828125 | 4 | import pandas as pd
# reads data and skips first row, last couple rows
couple_rows = [0, 1, 2]
df = pd.read_excel(r'A-1_NO_OF_VILLAGES_TOWNS_HOUSEHOLDS_POPULATION_AND_AREA.xlsx', skiprows=couple_rows)
df = df.iloc[:-28] # removes last 28 rows
# Step 1: remove all rows in col 6 with rural, urban, and subdistrict
print("\nStep 1: Ignore rural, urban, ignore subdistrict.")
print("**Note: Pandas dataframes show index as the first column but it is removed in the output")
df = df[~df[4].str.contains("SUB-DISTRICT")]
df = df[~df[4].str.contains("DISTRICT")]
df = df[~df[4].str.contains("INDIA")]
df = df[~df[6].str.contains("Rural")]
df = df[~df[6].str.contains("Urban")]
df = df.reset_index(drop = True)
print('\n')
print(df)
print("\nResult: india (1) + 35 (states +UTs) + 640 Districts = 676 records + headers")
print("Putting result in new file named: reduced-state.csv")
df.to_csv('reduced-state.csv', index=False, encoding='utf-8') |
688263175b4f1af97c5b432ae82297aa03b5d933 | Shreyankkarjigi/Python--Codes | /Problems on Lists/List to dictionary.py | 758 | 4.0625 | 4 | #Code by Shreyank #Github-https://github.com/Shreyankkarjigi
#problem
'''
input two lists from user one is key and one is value
convert the lists into dictionary
logic
input two lists
use zip function to combine both lists
use dict() function
'''
list_keys=[]
list_values=[]
r=int(input("Enter range"))
for i in range(r):
keys=input("Enter keys")
values=input("Enter values")
list_keys.append(keys)
list_values.append(values)
print("Dictionary formed\n")
print(dict(zip(list_keys,list_values)))
'''
output
Enter range5
Enter keys1
Enter values22
Enter keys2
Enter values33
Enter keys3
Enter values44
Enter keys4
Enter values55
Enter keys5
Enter values66
Dictionary formed
{'1': '22', '2': '33', '3': '44', '4': '55', '5': '66'}
'''
|
5e753b65e502e63f319b7058ada58c804c2401e6 | mbouchet98/ScriptPython | /test.py | 605 | 3.625 | 4 | from tkinter import *
from tkinter.messagebox import showinfo
fenetre = Tk()
#test = Label(fenetre, text='test')
#test.pack()
#bouton=Button(fenetre, text="Fermer", command=fenetre.quit)
#bouton.pack()
# tkinter pour lais des logiciel en python. c'est un mode fenetrer.
# sa y est je crois que j'adore python T-T .
def recupere():
showinfo("Alerte", entree.get())
value = StringVar()
value.set("Valeur")
entree = Entry(fenetre, textvariable=value, width=30)
entree.pack()
bouton = Button(fenetre, text="Valider", command=recupere)
bouton.pack()
fenetre.mainloop()
|
1a421e5336c5f1c57be3adaa0d5c79301eb5a14a | padmacho/pythontutorial | /objects/fun_return.py | 160 | 3.96875 | 4 | def modify(y):
return y # returns same reference. No new object is created
x = [1, 2, 3]
y = modify(x)
print("x == y", x == y)
print("x == y", x is y) |
e2bddfaf1aa9e10fb9e55ad5e0c78d7c33fb1a89 | BramvdnHeuvel/AdventOfCode2018 | /day_01/ex2_repetition.py | 342 | 3.5625 | 4 | sum = 0
sum_list = {sum}
number_found = False
while not number_found:
for line in open('input.txt', 'r'):
number = line.split('\n')[0]
number = int(number)
sum += number
if sum in sum_list:
print(sum)
number_found = True
break
sum_list.add(sum) |
14204cc21245289a64d7c92ef4ad266dfa0e9044 | jerekapyaho/eumemberdata | /populate.py | 877 | 3.859375 | 4 | import sqlite3
import csv
db_filename = 'eumemberdata.sqlite3'
def populate_table(conn, table_name):
with open(csv_filename, encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
columns = ', '.join([column for column in csv_reader.fieldnames])
values = ', '.join([':%s' % column for column in csv_reader.fieldnames])
statement = 'insert into %s (%s) values (%s)' % (table_name, columns, values)
cursor = conn.cursor()
cursor.executemany(statement, csv_reader)
conn.commit()
cursor.close()
table_names = ['country', 'country_name', 'city', 'city_name', 'union_name', 'membership']
for table_name in table_names:
csv_filename = table_name + '.csv'
print('Processing %s' % csv_filename)
conn = sqlite3.connect(db_filename)
populate_table(conn, table_name)
print('Done.')
|
2aac70afb9f1a8f0ce836593d7a638c7a0060276 | faizsiddiqui/Competitions | /Codechef/Practice-Beginner/ALPHABET.py | 292 | 3.828125 | 4 | # https://www.codechef.com/problems/ALPHABET
known = list(input())
words = int(input())
for word in range(words):
flag = False
for char in input():
if char not in known:
print("No")
flag = True
break
if not flag:
print("Yes")
|
c896734a34fda50543f8f3069dc3d55c5fcdd4e0 | cheonyeji/algorithm_study | /이코테/구현/q9_문자열압축.py | 1,233 | 3.546875 | 4 | # # 2021-01-26
# 이코테 ch12 구현 문제 Q9 문자열 압축
# https://programmers.co.kr/learn/courses/5/lessons/60057
INF = int(1e9)
def cut_str(s, num):
i = 0
length = len(s)
result = ""
while i < length:
str1 = s[i : i + num]
count = 1
for j in range(i + num, length, num):
if str1 == s[j : j + num]:
count += 1
else:
break
# 입출력예시 5번에서 제일 앞에서부터 정해진 길이만큼 잘라야한다고 나와있으므로 이 부분은 X
# if count == 1:
# result += s[i]
# i += 1
if count == 1:
result += str1
else:
result += str(count) + str1
i += num * count
return len(result)
def solution(s):
result = [INF] * (len(s) + 1)
# 문자열 길이가 1일때 for문을 안 돌아서 예외처리
if len(s) == 1:
result[1] = 1
for i in range(1, len(s)) // 2 + 1: # N/2까지의 모든 수만 살펴보면 됨
result[i] = cut_str(s, i)
return min(result)
"""
TC result
"aabbaccc" 7
"ababcdcdababcdcd" 9
"abcabcdede" 8
"abcabcabcabcdededededede" 14
"xababcdcdababcdcd" 17
"""
|
02744102c7e34059b1b17bf469e245dae43c6f3c | ctramm/Python_Training | /Udemy/Section 21/window_size.py | 539 | 3.78125 | 4 | """
Section 21: How to find the size of the window
"""
from selenium import webdriver
class WindowSize:
def demo(self):
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://letskodeit.teachable.com/p/practice")
driver.implicitly_wait(3)
height = driver.execute_script("return window.innerHeight;")
width = driver.execute_script("return window.innerWidth;")
print("Height: " + str(height))
print("Width: " + str(width))
c = WindowSize()
c.demo()
|
3b4902ad73a8463e97f64e63e3877bf6b6fa1273 | sbkaji/python-programs | /assignment/20.py | 618 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 01:25:24 2020
@author: Subarna Basnet
"""
"""20.Write a program to check if a year is leap year or not. If a year is divisible by 4 then it is leap year but if the year is century year like 2000, 1900, 2100 then it must be divisible by 400."""
year = int(input("Please Enter the Year Number you wish: "))
if (year%400 == 0):
print("%d is a Leap Year" %year)
elif (year%100 == 0):
print("%d is Not the Leap Year" %year)
elif (year%4 == 0):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
|
9cc4bc120926f61cb57458361059b32f4d2039fa | Dualve/Simple-programms | /fo1.py | 6,255 | 4.34375 | 4 | import math
while True:
print("""Выбирите нужную операцию:
1) Найти сумму цифр и количество цифр заданного натурального числа.
2) Возвести число в натуральную степень n.
3) Найти количество различных цифр у заданного натурального числа.
4) Найти наибольшую цифру натурального числа.
5) Задано натуральное число. Проверить, является ли заданое натуральное число палиндромом.
6) Определить является ли заданное натуральное число простым.
7) Найти все все простые делители заданного натурльного числа.
8) Найти НОД и НОК двух натурльных чисел.
9) Заданы три целых числа , которыю задают некоторую дату.\n Определить дату следующего дня.
10) Запрограммировать последовательность чисел Фибоначчи\n (пользователь вводит порядковый номер элемента \n последовательности Фибоначчи,а программа выводит на экран его значение.
0) Введите 0 чтобы покинуть программу.\n
""")
try:
choice = int(input())
except ValueError:
choice = 11
if choice == 1:
print("Выбран 1ый пункт меню.")
number_1 = input("Введите ваше число: ")
summa = 0
amount = 0
for i in number_1:
summa += int(i)
amount += 1
print("Сумма чисел =",summa,".\nКоличесвто цифр = ",amount,".")
elif choice == 2:
print("Выбран 2ой пункт меню.")
number_2 = int(input("Введите ваше число: "))
p = int(input("Введите натуральную степень n: "))
res = pow(number_2,p)
print("Итоговое число = ",res,".")
elif choice == 3:
print("Выбран 3ий пункт меню.")
amount_3 = 0
number_3 = set(input("Введите ваше число:"))
for i in number_3:
amount_3 += 1
print("Количество разных цифр в числе = ",amount_3,".")
elif choice == 4:
print("Выбран 4ый пункт меню.")
number_4 = int(input("Введите ваше число: "))
maximal = number_4%10
number_4 = number_4//10
while number_4 > 0:
if number_4 % 10 > maximal:
maximal = number_4 % 10
number_4 = number_4//10
print("Максимум =",maximal)
elif choice == 5:
print("Выбран 5ый пункт меню.")
number_5 = input("Введитее ваше число: ")
l_of_number = len(number_5)
for i in range(l_of_number//2):
if number_5[i] != number_5[-1-i]:
print("Число не палиндром.")
break
else:
print("Число палиндром.")
elif choice == 6:
print("Выбран 6ой пункт меню.")
number_6 = int(input("Введите ваше число: "))
max_divider = int(number_6//2)
for i in range(2,max_divider+1):
if number_6%max_divider == 0:
print(max_divider , "- делитель")
print("Число имеет более 3-х делителей из них: ",number_6,", 1, ",max_divider,".")
break
else:
max_divider -= 1
else:
print("Число простое.")
elif choice == 7:
print("Выбран 7ой пункт меню.")
number_7 = int(input("Введите ваше число: "))
divider = 0
for i in range(1,number_7):
if number_7%i == 0:
for n in range(2,i-1):
if i/n == 0:
print("Делитель ",i,"составной.")
else:
print(i,"- простой делитель.")
divider += 1
else:
continue
print("У заданного числа ",divider,"простых делителей.")
elif choice == 8:
print("Выбран 8ой пункт меню.")
a = int(input("Введите 1ое число: "))
b = int(input("Введите 2ое число: "))
def FIND_NOD(a,b):
while a != 0 and b != 0 :
if a > b:
a = a%b
else:
b = b%a
return a+b
print("НОД = ",FIND_NOD(a,b),".")
print("НОК = """,(a*b)/FIND_NOD(a,b),".")
elif choice == 9:
print("Выбран 9ый пункт меню.")
print("Программа в разработке.")
elif choice == 10:
print("Выбран 10ый пункт меню.")
amount_10 = int(input("Введите порядковый номер числа Фибоначчи: "))
number_10_1 = 1
number_10_2 = 1
print(number_10_1,number_10_2,end=" ")
for i in range (3,amount_10+1):
print(number_10_1+number_10_2,end=" ")
b = number_10_1
number_10_1 = number_10_2
number_10_2 = b + number_10_1
elif choice == 0:
print("До скорой встречи.")
break
else:
print("Введен некоректный пункт меню.") |
cd4076e501314f3d5fe5e563e8730f821fb853db | pingouin84/Mirror_Led | /test.py | 4,511 | 3.8125 | 4 | # Import a library of functions called 'pygame'
import pygame
from pygame.locals import *
from math import pi
import Matrice
# Initialize the game engine
pygame.init()
# Define the colors we will use in RGB format
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
h = {
(0,0): 'c',
(1,0): 'DROITE', (1,1): 'NE', (0,1): 'HAUT', (-1,1): 'NW',
(-1,0): 'GAUCHE', (-1,-1): 'SW', (0,-1): 'BAS', (1,-1): 'SE'
}
# Set the height and width of the screen
size = [400, 300]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Example code for the draw module")
# Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
#mon_joystick = pygame.joystick.Joystick
nb_joysticks = pygame.joystick.get_count()
if nb_joysticks > 0:
#if mon_joystick == pygame.joystick.Joystick:
mon_joystick = pygame.joystick.Joystick(0)
mon_joystick.init() #Initialisation
print("Axes :", mon_joystick.get_numaxes())
print("Boutons :", mon_joystick.get_numbuttons())
print("Trackballs :", mon_joystick.get_numballs())
print("Hats :", mon_joystick.get_numhats())
while not done:
# This limits the while loop to a max of 10 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(10)
#On compte les joysticks
nb_joysticks = pygame.joystick.get_count()
#Et on en crée un s'il y a en au moins un
if nb_joysticks > 0:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
if event.type == JOYBUTTONDOWN:
print(event.button)
if event.type == KEYDOWN:
print(event.key)
if event.type == MOUSEBUTTONDOWN:
print(event.button)
if event.type == JOYAXISMOTION:
if event.axis == 0 and event.value > 0:
print("droite %d",event.value)
if event.axis == 0 and event.value < 0:
print("gauche %d",event.value)
if event.type == JOYHATMOTION:
print(event.hat,h[event.value])
#if event.Hats == 0 and event.value > 0:
#print("droite %d",event.value)
#if event.axis == 0 and event.value < 0:
#print("gauche %d",event.value)
#if event.type != 7:
#print(event.type)
# All drawing code happens after the for loop and but
# inside the main while done==False loop.
# Clear the screen and set the screen background
screen.fill(WHITE)
pygame.draw.rect(screen, Matrice.Matrice.BLUE, [1*10, 1*10, 10, 10])
# Draw on the screen a GREEN line from (0,0) to (50.75)
# 5 pixels wide.
pygame.draw.line(screen, GREEN, [0, 0], [50, 30], 5)
# Draw on the screen a GREEN line from (0,0) to (50.75)
# 5 pixels wide.
pygame.draw.lines(
screen, BLACK, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5
)
# Draw on the screen a GREEN line from (0,0) to (50.75)
# 5 pixels wide.
pygame.draw.aaline(screen, GREEN, [0, 50], [50, 80], True)
# Draw a rectangle outline
pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2)
# Draw a solid rectangle
pygame.draw.rect(screen, BLACK, [150, 10, 50, 20])
# Draw an ellipse outline, using a rectangle as the outside boundaries
pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2)
# Draw an solid ellipse, using a rectangle as the outside boundaries
pygame.draw.ellipse(screen, RED, [300, 10, 50, 20])
# This draws a triangle using the polygon command
pygame.draw.polygon(screen, BLACK, [[100, 100], [0, 200], [200, 200]], 5)
# Draw an arc as part of an ellipse.
# Use radians to determine what angle to draw.
pygame.draw.arc(screen, BLACK, [210, 75, 150, 125], 0, pi / 2, 2)
pygame.draw.arc(screen, GREEN, [210, 75, 150, 125], pi / 2, pi, 2)
pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi, 3 * pi / 2, 2)
pygame.draw.arc(screen, RED, [210, 75, 150, 125], 3 * pi / 2, 2 * pi, 2)
# Draw a circle
pygame.draw.circle(screen, BLUE, [60, 250], 40)
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# Be IDLE friendly
pygame.quit()
|
cb337e45c437ed7495d7b4c0bab7912f9547bb02 | diogodutra/employee_manager_py | /Employee.py | 646 | 3.796875 | 4 | class Employee(object):
#public members
name = ""
id = ""
rate_hourly = 0
hours_monthly = 0
#constructor
def __init__(self, name, id, rate_hourly, hours_monthly):
self.name = name
self.id = id
self.rate_hourly = rate_hourly
self.hours_monthly = hours_monthly
#destructor
def __del__(self):
#body of destructor
pass
def __str__(self):
return str(self.id) + ", " + str(self.name) + ", " + str(self.hours_monthly) + "h, $" + str(self.rate_hourly) + "/h"
#public methods
def get_salary(self):
return self.rate_hourly * self.hours_monthly
def get_name(self):
return self.name |
7a2dfb870f4acaf2d27e5c971d705af7504e5d74 | swapnilkathane/Practice_3 | /list modify.py | 280 | 3.796875 | 4 | L1=[1,2,3,4,5,5,6]
b=len(L1)
n=0
L2=[]
while(n<b):
for x in L1:
if x in L2:
#m=1 #to print duplicate elements only once
L2.remove(x) #to remove the duplicate elements in list
else:
L2.append(x)
n+=1
print(L2)
|
663650b91c2e06351a39e83816848c7ee721530c | RobsonGomes1/SIMULADOR-DE-DADO | /Simulador_de_dados.py | 1,290 | 3.65625 | 4 | try:
dados = [ 1, 2, 3, 4, 5, 6, 7 ,8 ,9 ,10]
except:
print('Error... Invalid code')
else:
op = 0
while op != 2:
print('-' *10, 'Jogando dado', '-' *10)
print('Opção: Escrava [1] para jogar '.strip().upper())
print('Opção: Escreva [2] para sair'.strip().upper())
op = int(input('Qual opção: \n'.strip()))
if op == 1:
op1 = int(input('Qual numero irá cair!? \n'))
from time import sleep
from random import randint
sor = randint(1, 10)
print('Analisando...')
sleep(1)
print('Dado jogado...')
sleep(1.3)
print('Girando...')
sleep(0.7)
print('Resultado é:\n....')
sleep(0.0)
print('Resultado: {} do valor escolhido: {}'.format(sor, op1))
sleep(0.1)
elif op == 2:
from time import sleep
print('Finalizando...')
sleep(0.1)
else:
from time import sleep
print('................')
sleep(1.1)
print('................')
sleep(1.1)
print('Operação não reconhecida')
sleep(1.0)
finally:
print('Volte Sempre! Very Ty. :)')
|
dc1fdecddf0baefd361bb7bd35089cba195dd6fd | rick-62/AdventOfCode2017 | /day22/day22.py | 3,586 | 3.546875 | 4 | # day22
import sys
class Puzzle():
def __init__(self, test_flag=False):
if test_flag:
self.nodes = self.load_into_memory("test.txt")
else:
self.nodes = self.load_into_memory("input.txt")
self.infect_count = 0
self.direction = 'N'
self.current_node = self.start_coord()
def load_into_memory(self, filename):
"""load input into memory"""
dct = {}
with open(filename) as f:
all_lines = f.readlines()
for y, line in enumerate(all_lines[::-1]):
for x, node in enumerate(line.strip('\n')):
dct[(x, y)] = node
return dct
def solve_part1(self, n=10000):
"""part 1"""
for _ in range(n):
self.next_direction()
self.update_current_node()
self.move_carrier()
return self.infect_count
def start_coord(self):
"""return start coordinate"""
centre = int((len(self.nodes.keys()) ** 0.5) // 2)
return (centre, centre)
@property
def node_status(self):
"""retrieve value from self.nodes else clean"""
return self.nodes.get(self.current_node, '.')
def next_direction(self):
"""based on current position which direction next"""
compass = ['N', 'E', 'S', 'W']
i_compass = compass.index(self.direction)
if self.node_status == '.': # turn left
new_direction = compass[i_compass - 1]
elif self.node_status == '#': # turn right
new_direction = compass[(i_compass + 1) % 4]
elif self.node_status == 'W': # no turn
new_direction = self.direction
elif self.node_status == 'F': # reverse
new_direction = compass[(i_compass + 2) % 4]
else:
print("error: check current node")
self.direction = new_direction
def update_current_node(self):
"""change current node infection"""
if self.node_status == '.':
new_status = '#'
self.infect_count += 1
else:
new_status = '.'
self.nodes[self.current_node] = new_status
def move_carrier(self):
"""virus carrier moves forwards one node"""
compass = {'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0)}
zipped = zip(compass[self.direction], self.current_node)
self.current_node = tuple([sum(x) for x in zipped])
def solve_part2(self, n=10000000):
"""part 2"""
for _ in range(n):
self.next_direction()
self.update_current_node_2()
self.move_carrier()
return self.infect_count
def update_current_node_2(self):
"""change current node infection - part 2"""
if self.node_status == '.':
new_status = 'W'
elif self.node_status == 'W':
new_status = '#'
self.infect_count += 1
elif self.node_status == '#':
new_status = 'F'
elif self.node_status == 'F':
new_status = '.'
else:
print("error: current node not identified")
self.nodes[self.current_node] = new_status
if __name__ == '__main__':
test_flag = True if 'test' in sys.argv else False
puzzle = Puzzle(test_flag)
part1 = puzzle.solve_part1()
print("part1:", part1)
puzzle_2 = Puzzle(test_flag)
part2 = puzzle_2.solve_part2()
print("part2:", part2)
if test_flag:
print("testing complete successfully")
|
806a30de3fb7c1e846d5031b4476ab58e2d959ab | mooja/dailyprogrammer | /challenge89easy.py | 1,924 | 3.984375 | 4 | #!/usr/bin/env python
# encoding: utf-8
# Daily Programmer Challenge 89 Easy
#
# http://www.reddit.com/r/dailyprogrammer/comments/yj2zq/8202012_challenge_89_easy_simple_statistical/
#
# March.02.2015
import math
def mean(xs):
""" mean([ints...]): return the arithmetic mean (average) of the input
sequence
>>> mean([1, 2, 3])
2.0
"""
return sum(xs) / float(len(xs))
def variance(xs):
""" variance([ints...]): return the average of the squared differnces
from the mean
>>> variance([1, 1, 1])
0.0
"""
mean_ = mean(xs)
squared_difference = [(x-mean_)**2 for x in xs]
variance_ = mean(squared_difference)
return variance_
def stddev(xs):
""" stddev([ints...]): return standard deviation: the square root of
the variance
>>> stddev([1, 1, 1])
0.0
"""
_variance = variance(xs)
return math.sqrt(_variance)
if __name__ == '__main__':
import doctest
doctest.testmod()
data = """
0.4081
0.5514
0.0901
0.4637
0.5288
0.0831
0.0054
0.0292
0.0548
0.4460
0.0009
0.9525
0.2079
0.3698
0.4966
0.0786
0.4684
0.1731
0.1008
0.3169
0.0220
0.1763
0.5901
0.4661
0.6520
0.1485
0.0049
0.7865
0.8373
0.6934
0.3973
0.3616
0.4538
0.2674
0.3204
0.5798
0.2661
0.0799
0.0132
0.0000
0.1827
0.2162
0.9927
0.1966
0.1793
0.7147
0.3386
0.2734
0.5966
0.9083
0.3049
0.0711
0.0142
0.1799
0.3180
0.6281
0.0073
0.2650
0.0008
0.4552
"""
data = [float(x) for x in data.strip().split()]
print("mean: {}".format(mean(data)))
print("variance: {}".format(variance(data)))
print("std. deviation: {}".format(stddev(data)))
|
cd1d0c8890b813b90d1edf21de2555ff70687692 | marvely/python_data_structures | /object_sample_code.py | 1,365 | 4.21875 | 4 | class PartyAnimal:
x = 0
name = ""
def __init__(self, nam):
self.name = nam
print "I am constructed"
def party(self): #<--- first parameter, and at least one
self.x = self.x + 1
print self.name, "party count", self.x
#def __del__(self): #<---- only happens at the end of the program...
# print "I am destructed", self.x
#an = PartyAnimal()
#an.party() # <-- make an object, and can call the party() on it
#an.party()
#an.party()
'''
PartyAnimal.party(an) #<----- self becomes an alies of an.
'''
# what we really doing is making new kinds of things~ can use dir and type() to find out
#print "Type:", type (an)
#print "Dir:", dir(an) # print all the methods
'''
the methods with double underscores are for methods when certain things happen, the certain code will get run
'''
s = PartyAnimal("Sally")
s.party()
j = PartyAnimal("JIm")
j.party()
s.party() #<-- the 2nd time it runs, should return 2
'''
j and s are Independent instances
'''
# create a new class using the existing code above:
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
self.points = self.points + 7
self.party() #<------- inherited from the party animal class and puts here
print self.name, "points", self.points #<---------- new thing for FootballFan class!
k = FootballFan("Karl")
#k.party()
k.touchdown() |
0e50d8ed71b2789285f689cfb2bb7ea379c15ec0 | jawbreakyr/LPTHW-exercises | /Documents/tutorials/python-docs/filteringdecode.py | 1,155 | 3.921875 | 4 | """
filtering an encrypted file(not mine just copied,
hopefully to unserstand it and rewrite it the way
i will understand to solve the problem.)
"""
import string
file_ = open('solutions.txt', 'r')
text = ''.join(file_.readlines())
def get_unique(text):
"""
gets the "characters" in "text" = solutions.txt
if character is not in "new_text"
then put in the new_text variable.
"""
new_text = ''
for character in text:
if character not in new_text:
new_text += character
return new_text
def get_characters(text, exclude):
"""
gets the charater in text = solution.txt
if character is not in "exclude" variable
append the character to the symbols variable.
"""
symbols = ''
for character in text:
if character not in exclude:
symbols += character
return symbols
unique = get_unique(text)
print "this is unique: %s" % unique
alphabet = string.ascii_lowercase
print "this is the alphabet: %s" % alphabet
symbols = get_characters(unique, alphabet)
print "this is the symbols: %s" % symbols
letters = get_characters(unique, symbols)
# print letters |
f700ccf4344d4a6dfe61291fcdc6dd56e11db4e7 | doanthanhnhan/learningPY | /01_fundamentals/02_operators/string.py | 795 | 4.4375 | 4 | # Comparison Operators
print('a' < 'b') # 'a' has a smaller Unicode value
house = "Gryffindor"
house_copy = "Gryffindor"
print(house == house_copy)
new_house = "Slytherin"
print(house == new_house)
print(new_house <= house)
print(new_house >= house)
# Concatenation
first_half = "Bat"
second_half = "man"
full_name = first_half + second_half
print(full_name)
# The * operator allows us to multiply a string, resulting in a repeating pattern:
print("ha" * 3)
# Search
# The in keyword can be used to check if a particular substring exists in another string.
# If the substring is found, the operation returns true.
random_string = "This is a random string"
print('of' in random_string) # Check whether 'of' exists in randomString
print('random' in random_string) # 'random' exists!
|
c15154551319311c0a335ff53022e24a3b2ba546 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2604/60889/266188.py | 230 | 4 | 4 | letters = input().strip("[\"]").split("\", \"")
target = input()
answer = letters[0]
for letter in letters:
if (letter>target>=answer) or (answer>letter>target) or (target>=answer>letter):
answer = letter
print(answer) |
d94b280b34090c6b8b32e135a107a0671aedc516 | rkdntm1/Python_practice | /main.py | 913 | 3.65625 | 4 | # 과제) 목록에 어떤 알파벳이 있는지 소스 짜오기
# ('hong', 'kim', 'lee','park','kim') -> 알파벳 만
# 중복 없는 리스트 형태로 변경
def make_list(*arr):
irum = []
for item in arr:
if item not in irum: # 중복 없애주기
irum.append(item)
return irum
# 리스트안의 내용을 합쳐서 str 형태로 변경해주기
def strchanger(lst):
k = ''
for i in range(len(t1)):
k += t1[i]
return k
# str 형에서 중복 없이 알파벳 단위로 뽑아 내는 함수
def alpha(str):
mas = []
for j in range(len(str)):
if str[j] not in mas: # 중복 없애주기
mas += str[j]
return mas
t1 = make_list('hong', 'kim', 'lee', 'park', 'kim') # make_list 함수 호출
p = strchanger(t1) # strchanger 함수 호출
f = alpha(p) # aplpha 함수 호출
f.sort()
print(f) # 결과 출력
|
5fa30bdc896aea2b927487541e253b582c892c52 | bhaskarv/LearnPython | /tuples.py | 555 | 4.40625 | 4 | #tuples are like immutable lists they can't be modified
list_1=['History','Maths','Physics','CompSci']
list_2=list_1
print(list_1)
print(list_2)
list_1[0]='Arts'
#As can be seen below, adding to list_1 changed list_2 as well
print(list_1)
print(list_2)
#now take a look at a tuple
touple_1=('History','Maths','Phisics','CompSci')
touple_2 = touple_1
print(touple_1)
print(touple_2)
#trying to modify hte touple gives error
touple_1[0]='Arts'
#Guideline : If you want to access and modfiy use list, if you just want to iterate and access use touple |
b3bf3455c2283d65c1feebf9a4de642abfbb97df | FrozenLi/prob6 | /hashFunction.py | 799 | 3.78125 | 4 | import math
class hashFunction:
def __init__(self, a, b, p, M):
self.a = a
self.b = b
self.p = p
self.M = M
def hash(self, x):
# using same logic of java.lang.string hashCode function to convert string to int
# https://en.wikipedia.org/wiki/Java_hashCode()
if isinstance(x, int):
result = ((self.a * x + self.b) % self.p) % self.M
else:
# Convert to String
x = str(x)
# Convert x to integer
str_to_int = 0
for i in range(0, len(x)):
str_to_int += ord(x[i]) * math.pow(31, len(x) - 1 - i)
# Use hash function to hash integer
result = ((self.a * int(str_to_int) + self.b) % self.p) % self.M
return result
|
66c484473e7d17af698ddc31c1bae87ba5d94e28 | gauripatil20/LIST | /LIST_24_EVEN.PY | 133 | 3.65625 | 4 | # i=0
# b=[]
# while i<10:
# num=int(input("enter the number"))
# if num%2==0:
# b.append(num)
# i=i+1
# print(b) |
8c5c8f040ee96c22c19d0c782689d6bfd8cdb92d | charansaim1819/Python_Patterns | /ALPHABETS/SMALL_ALPHABETS/x.py | 644 | 3.984375 | 4 | #Shape of small x:
def for_x():
"""printing small 'x' using for loop"""
for row in range(5):
for col in range(5):
if row%4==0 and col!=2 or col==2 and row not in(0,4):
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_x():
"""printing small 'x' using while loop"""
i=0
while i<4:
j=0
while j<5:
if j!=2 and i%3==0 or j==2 and i in(1,2):
print("*",end=" ")
else:
print(" ",end=" ")
j+=1
print()
i+=1
|
59a0986bc6860280e5b198596963b1c26a3731b1 | charan2108/pyprocharmprojects | /pythoncrashcourse/Statements/if.py | 1,661 | 4.3125 | 4 | cars = ['audi', 'benz', 'cheverolet', 'etiga','ferrai']
print(cars)
print("\n")
if cars == 'audi':
print(cars.upper())
# adding else statement
if cars == 'audi':
print(cars.upper())
else:
print(cars)
# checking for inequality
requested_cars = 'mercedes'
if requested_cars != 'ferrari':
print("Hold the mercedes")
# checking a user is in banned list or not
banned_users = ['a','b', 'c']
user = 'e'
if user not in banned_users:
print(user.title() + " you can post the response or post"+"!")
# factor to determine the voting age
age = eval(input("Enter your age"))
if age>=18:
print("Eligible to vote")
else:
print("Register to voye when you turn 18")
#School Admission
age = eval(input("Enter your age"))
if age <=12:
print("The admission is free")
elif age <=18:
print("The admission cost is 5 $")
else:
print("The admision cost is 100$")
requested_toppings = ['mushrooms', 'macroni', 'cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms")
if 'macroni' in requested_toppings:
print(' Addming macroni')
print(" added the toppings in the pizza")
pizza_toppings = input("Enter the toppings")
avaialable_toppings = ['mushrooms', 'pepper', 'pepporoni', 'cheese', 'pineapple', 'tomato']
requested_toppings=['mushrooms', 'pepper', 'pepporoni', 'cheese']
for requested_topping in requested_toppings:
if requested_topping in avaialable_toppings:
print("Adding " + requested_topping +"!")
else:
print("Sorry the requested toppings is not avaialbale!")
print("\n finished making the requested pizza") |
cce5d172f7a3fd627b6145e9110c0e2b9aca73d2 | raxaminhal/Python-Programming-Assignmsnts | /Assignment-1.py | 854 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print(now)
# In[1]:
from math import pi
r = float(input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
# In[2]:
import sys
print("Python version")
print (sys.version)
# In[4]:
fname = input("Input your First Name : ")
lname = input("Input your Last Name : ")
print (lname + " " + fname)
# In[6]:
a = int(input("enter first number: "))
b = int(input("enter second number: "))
sum = a + b
print(sum)
# In[7]:
print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!")
# In[ ]:
|
873295b24880ac6e13873ecb13eb1a10498efe56 | alem-classroom/student-python-introduction-nzekenov | /loops-for/arrayLoop.py | 179 | 4.03125 | 4 | def insert_squares(arr, num):
# add square of numbers from 1 to num to the list named arr and return list
for i in range(num):
arr.append((i+1)*(i+1))
return arr |
f3989fc5cb174eb58d3521d0a2d4d6bd7beba61a | andrewsihotang/sisterchatapp | /client.py | 5,226 | 3.59375 | 4 | #menggunakan GUI library Tkinter
import tkinter as tk
from tkinter import messagebox
#untuk socket
import socket
#untuk thread
import threading
window = tk.Tk()
window.title("Client")
username = " "
frameAtas = tk.Frame(window)
isiUsername = tk.Label(frameAtas, text = "Name:").pack(side=tk.LEFT) #isi name dari client
isiUsername2 = tk.Entry(frameAtas) #menampilkan box untuk isi nama
isiUsername2.pack(side=tk.LEFT) #menampilkan box untuk isi nama
tombolConnect = tk.Button(frameAtas, text="Connect", command=lambda : connect()) #button connect client
tombolConnect.pack(side=tk.LEFT)
frameAtas.pack(side=tk.TOP) #menampilkan nama dan button connect diatas
displayFrame = tk.Frame(window)
lblLine = tk.Label(displayFrame, text=" ").pack()
scrollBar = tk.Scrollbar(displayFrame) #untuk slide controller
scrollBar.pack(side=tk.RIGHT, fill=tk.Y) #tampilkan slide controller
tkDisplay = tk.Text(displayFrame, height=20, width=55) #framenya
tkDisplay.pack(side=tk.LEFT, fill=tk.Y, padx=(5, 0))
tkDisplay.tag_config("tag_your_message", foreground="blue") #untuk membuat message sendiri menjadi biru
scrollBar.config(command=tkDisplay.yview)
tkDisplay.config(yscrollcommand=scrollBar.set, background="#F4F6F7", highlightbackground="grey", state="disabled")
displayFrame.pack(side=tk.TOP) #untuk menampilkan pesan displaynya
frameBawah = tk.Frame(window)
kirimPesan = tk.Text(frameBawah, height=2, width=55) #size
kirimPesan.pack(side=tk.LEFT, padx=(5, 13), pady=(5, 10))
kirimPesan.config(highlightbackground="grey", state="disabled")
kirimPesan.bind("<Return>", (lambda event: getPesanChat(kirimPesan.get("1.0", tk.END))))
frameBawah.pack(side=tk.BOTTOM) #menampilkan dibawah
# ketika button click ditrigger akan memanggil fungsi connect ini
# fungsi ini mengecek username apakah sudah di masukkan sebelum mencoba untuk connect ke server
# setelah itu akan memanggil fungsi connectKeServer
def connect():
global username, client
if len(isiUsername2.get()) < 1:
#memunculkan error kalau belum tulis nama sebelum connect
tk.messagebox.showerror(title="ERROR!!!", message="You must enter a name!")
else:
username = isiUsername2.get()
connectKeServer(username)
# network client
client = None
alamatHost = "192.168.1.4"
alamatPort = 5000
# fungsi untuk connect ke server
def connectKeServer(name):
global client, alamatPort, alamatHost
try:
# buat client socket IPv4 (socket.AF_INET) dan TCP protocol (socket.SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((alamatHost, alamatPort))
client.send(name.encode()) # mengirim nama ke server setelah connecting
isiUsername2.config(state=tk.DISABLED)
tombolConnect.config(state=tk.DISABLED)
kirimPesan.config(state=tk.NORMAL)
# memulai thread untuk terus menerima message dari server
threading._start_new_thread(menerimaPesanDariServer, (client, "m"))
except Exception as e:
# menampilkan pesan error ketika tidak bisa connect ke ip ataupun port yang dituju
tk.messagebox.showerror(title="ERROR!!!", message="Cannot connect to host: " + alamatHost + " on port: " + str(alamatPort) + ". Try again later")
# fungsi ini yaitu, loop yang dibuat untuk terus menerima message dari server (via client socket)
# pesan yang diterima akan di tambahkan di client chat display area
def menerimaPesanDariServer(sck, m):
while True:
from_server = sck.recv(4096).decode() #buffer size
if not from_server: break
# menampilakan message dari server di window chat
# enable the display area and insert the text and then disable
texts = tkDisplay.get("1.0", tk.END).strip()
tkDisplay.config(state=tk.NORMAL)
if len(texts) < 1:
tkDisplay.insert(tk.END, from_server)
else:
tkDisplay.insert(tk.END, "\n\n"+ from_server)
tkDisplay.config(state=tk.DISABLED)
tkDisplay.see(tk.END)
sck.close() # tutup koneksi
window.destroy() # tutup window
def getPesanChat(pesan):
pesan = pesan.replace('\n', '')
texts = tkDisplay.get("1.0", tk.END).strip()
# enable area displaynya lalu insert pesan dan disable kembali
tkDisplay.config(state=tk.NORMAL) #enable
if len(texts) < 1:
# untuk konfigurasi message yang masuk, merubah menjadi text biru
tkDisplay.insert(tk.END, "You->" + pesan, "tag_your_message")
else:
tkDisplay.insert(tk.END, "\n\n" + "You->" + pesan, "tag_your_message")
tkDisplay.config(state=tk.DISABLED) #disable
# memanggil fungsi kirimPesanKeServer agar client-client yang connect dapat melihat semua pesan
kirimPesanKeServer(pesan)
tkDisplay.see(tk.END)
kirimPesan.delete('1.0', tk.END)
# mengirim pesan ke server dengan menggunakan send function dari socket object
# lalu close client socket dan menutup chat window jika user mengetik pesan exit
def kirimPesanKeServer(pesan):
pesanClient = str(pesan)
client.send(pesanClient.encode())
if pesan == "exit":
client.close() # tutup koneksi
window.destroy() # tutup window
print("Sending message") #di terminal
window.mainloop() |
35c92c4e4616af9d58f850523df5b63e1f149e63 | CoderLeechou/LeetCode-Python | /015ThreeSum/Ts.py | 1,649 | 3.6875 | 4 | #-*-coding:utf-8-*-
class Solution(object):
'''
题意:求数列中三个数之和为0的三元组有多少个,需去重
暴力枚举三个数复杂度为O(N^3)
先考虑2Sum的做法,假设升序数列a,对于一组解ai,aj, 另一组解ak,al
必然满足 i<k j>l 或 i>k j<l, 因此我们可以用两个指针,初始时指向数列两端
指向数之和大于目标值时,右指针向左移使得总和减小,反之左指针向右移
由此可以用O(N)的复杂度解决2Sum问题,3Sum则枚举第一个数O(N^2)
使用有序数列的好处是,在枚举和移动指针时值相等的数可以跳过,省去去重部分
'''
def threeSum(self,nums):
nums.sort()
res=[]
length=len(nums)
for i in range(0,length-2):
if i and nums[i]==nums[i-1]:
continue
target=nums[i]*-1
left,right=i+1,length-1
while left<right:
if nums[left]+nums[right]==target:
res.append([nums[i],nums[left],nums[right]])
right-=1
left+=1
while left<right and nums[left]==nums[left-1]:
left+=1
while left<right and nums[right]==nums[right+1]:
right-=1
elif nums[left]+nums[right]>target:
right-=1
else:
left+=1
return res
if __name__=='__main__':
nums=[-1, 0, 1, 2, -1, -4]
print Solution().threeSum(nums)
|
2974668739f32142045c9f3f24db51afadb9c99f | lochappy/video_sequence_arrangement | /video_sequence_arrangement.py | 3,564 | 4.21875 | 4 | '''
Author: Loc Truong <ttanloc@gmail.com>
Date: 16Jan2021
Brief: This is the video-sequence arrangement algorithm
Usage:
> python3 video_sequence_arrangement.py -v Path/to/video/file -s Path/to/sequence/file
'''
from argparse import ArgumentParser
def foobar(video_list, sequence, start_index=0, list_of_selected_videos=[]):
'''
This function arranges the list of videos to the sequence.
@param:
input: video_list: list of videos, in the form of [(Name0,length0), (Name1,length1)...]
sequence: list of sequence of scenes, in form of [True, False, True...]
start_index: start index location of the current sequence.
list_of_selected_videos: list of the videos included in the previous iteration
output: return the list of possible locations of the video list in the sequence
'''
# if total length of the video is greater than the sequence, return []
total_length = 0
for video in video_list:
total_length += video[1]
if total_length > len(sequence):
return []
# base case: empty video list or sequence
if len(video_list) == 0 or len(sequence) == 0:
return []
curr_video_name, curr_video_len = video_list[0]
# base case: there is only one video in the list
if len(video_list) == 1:
possible_postions_of_last_video = []
for index in range(start_index,len(sequence)):
if sequence[index] and (index + curr_video_len) <=len(sequence):
possible_postions_of_last_video.append(list_of_selected_videos + [(curr_video_name, index)])
return possible_postions_of_last_video
# Normal cases: there are more than one video in the list
possible_postions_of_videos = []
for index in range(start_index,len(sequence)):
if sequence[index] and (index + curr_video_len)<=len(sequence):
new_possible_locations = foobar(video_list[1:], sequence, index + curr_video_len, list_of_selected_videos + [(curr_video_name, index)])
possible_postions_of_videos = possible_postions_of_videos + new_possible_locations
return possible_postions_of_videos
if __name__ == "__main__":
# parse the argument
parser = ArgumentParser(description='Arrange video list to the sequence')
parser.add_argument('-v', metavar='Path/to/text/file', type=str, required=True, dest='video_list',
help='Path to text file containing list of video')
parser.add_argument('-s', metavar='Path/to/text/file', type=str, required=True, dest='sequence',
help='Path to text file containing sequence of scene')
args = parser.parse_args()
# read the sequence file
with open(args.sequence,'r') as f:
sequence = [line == 'T' for line in f.read().splitlines()]
# read the video list
with open(args.video_list,'r') as f:
video_list = [line.split(',') for line in f.read().splitlines()][1:]
video_list = [ (video[0], int(video[1])) for video in video_list]
# compute the possible location of the video list
possible_locations = foobar(video_list, sequence)
# print out the result.
if possible_locations:
print('\n###### Possible arrangement #######\n')
for pos in possible_locations:
print(pos)
print('\n##################################\n')
else:
print('\n##################################')
print('## No possible arrangement found #')
print('##################################\n')
|
6d5afe8c12755ca902f5e69642c48cbdd55a1880 | Nero5023/Algorithm | /CtCI/17-8.py | 860 | 3.578125 | 4 | # -*- coding:utf-8 -*-
class MaxSum:
def getMaxSum(self, A, n):
# write code here
arr = A
maxSum = arr[0]
start = 0
end = 0
for index in range(1,len(arr)):
val = arr[index]
if val <= 0:
if maxSum < val:
maxSum = val
start = index
end = index
continue
else:
continue
# val > 0
copyStart = start
for i in range(copyStart, index+1):
sumVal = sum(arr[i:index+1])
if sumVal > maxSum:
maxSum = sumVal
start = i
end = index
return maxSum
if __name__ == '__main__':
print MaxSum().getMaxSum([-56,7,-129,-71,3,-119],6)
|
9cc41854310cbb949fca51ed3e27354cce992a2e | JIghtuse/python-playground | /crash_course/lists/modifying_lists.py | 1,722 | 4.03125 | 4 | guests = ['Dan Simmons', 'Stephen King', 'Robert Sheckley']
print(f"Dear {guests[0]}, please join our dinner today.")
print(f"Dear {guests[1]}, please join our dinner today.")
print(f"Dear {guests[2]}, please join our dinner today.")
cant_make_the_dinner = 'Robert Sheckley'
new_guest = 'Neal Stephenson'
print(f"\n{cant_make_the_dinner} will not join us, unfortunately.")
guests.remove(cant_make_the_dinner)
guests.append(new_guest)
print(f"Dear {guests[0]}, please join our dinner today.")
print(f"Dear {guests[1]}, please join our dinner today.")
print(f"Dear {guests[2]}, please join our dinner today.")
print("\nDear guests, we found a bigger dinner table!")
guests.insert(0, 'George Martin')
guests.insert(3, 'Neil Gaiman')
guests.append('William Gibson')
print(f"Dear {guests[0]}, please join our dinner today.")
print(f"Dear {guests[1]}, please join our dinner today.")
print(f"Dear {guests[2]}, please join our dinner today.")
print(f"Dear {guests[3]}, please join our dinner today.")
print(f"Dear {guests[4]}, please join our dinner today.")
print(f"Dear {guests[5]}, please join our dinner today.")
print(f"We are inviting {len(guests)} people to dinner.")
print("\nDear guests, our table won't arrive in time for the dinner. We can only invite two people.")
guest = guests.pop()
print(f"Dear {guest}, sorry, but we can't invite you to dinner.")
guest = guests.pop()
print(f"Dear {guest}, sorry, but we can't invite you to dinner.")
guest = guests.pop()
print(f"Dear {guest}, sorry, but we can't invite you to dinner.")
guest = guests.pop()
print(f"Dear {guest}, sorry, but we can't invite you to dinner.")
print(f"Dear {guests[0]}, please join our dinner today.")
print(f"Dear {guests[1]}, please join our dinner today.")
del guests[1]
del guests[0]
print(guests)
|
20c664415015d09fb3f238572e848d07ce4ceae1 | dalq/python-cookbook | /cookbook/one/2SplitArbitrarySequence.py | 495 | 4.3125 | 4 | #从任意长度的可迭代对象中分解元素
record = ('name', 'addr', 'tel', 'tel2')
name, addr, *tel = record
print(name)
print(addr)
print(tel)
*before, after = [1, 2, 3, 4, 5, 6]
print(before)
print(after)
# 在循环中也好使
record = [('foo', 1, 2), ('bar', 'hello'), ('foo', 5, 6)]
def do_foo(x, y):
print('foo', x, y)
def do_bar(s):
print('bar', s)
for tag, *tags in record:
if tag == 'foo':
do_foo(*tags)
elif tag == 'bar':
do_bar(tags)
|
7fc7a858d58bdff03789fde44724402e108f26c2 | buptwxd2/leetcode | /Round_1/733. Flood Fill/solution_1.py | 1,126 | 3.53125 | 4 | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
row = len(image)
col = len(image[0])
points = []
target = image[sr][sc]
visited = {}
def dfs(sr, sc):
nonlocal points
if sr < 0 or sr > row - 1:
return
if sc < 0 or sc > col - 1:
return
if image[sr][sc] != target:
return
if [sr, sc] not in points:
points.append([sr, sc])
else:
return
# move left:
dfs(sr, sc - 1)
# move right
dfs(sr, sc + 1)
# move up
dfs(sr - 1, sc)
# move down
dfs(sr + 1, sc)
dfs(sr, sc)
def fillup_new_color(image, points, new_color):
for x, y in points:
image[x][y] = new_color
new_image = image.copy()
fillup_new_color(new_image, points, newColor)
return new_image
"""
Results:
DFS using recursive way
""" |
ecb5fdec977cbc92797e94bad8cc5d00fc9d634b | TianqGuo/PythonJavaProblemsSummary | /Tests.py | 5,694 | 3.703125 | 4 | import sys
import copy
# quick select
class solution(object):
def quickSelect(self, array, target):
if not array:
return array
if target >= len(array):
return sys.minint
self.partition(array, 0, len(array) - 1, target)
return array[target]
def partition(self, array, left, right, target):
if left >= right:
return
pivotIndex = int(left + (right - left) / 2)
pivot = array[pivotIndex]
i = left
j = right
array[right], array[pivotIndex] = array[pivotIndex], array[right]
j -= 1
while i <= j:
if array[i] < pivot:
i += 1
elif array[j] >= pivot:
j -= 1
else:
array[i], array[j] = array[j], array[i]
i += 1
j -= 1
array[right], array[i] = array[i], array[right]
if i > target:
self.partition(array, left, i - 1, target)
elif i < target:
self.partition(array, i + 1, right, target)
# print(solution().quickSelect([1, 6, 2, 4, 3, 3, 3, 8, 7], 4))
# deduplicated
class Solution(object):
def dedup(self, array):
"""
input: int[] array
return: int[]
"""
# write your solution here
slow = 0
for fast in range(1, len(array)):
if array[fast] != array[slow]:
slow += 1
array[slow], array[fast] = array[fast], array[slow]
print(slow)
return array[:slow + 1]
# print(Solution().dedup([1, 1, 2, 2, 2]))
# MergeSort
class Solution(object):
def mergeSort(self, array):
"""
input: int[] array
return: int[]
"""
# write your solution here
return self.mergeRecursion(array, 0, len(array) - 1)
def mergeRecursion(self, array, left, right):
# print (left, right)
if left >= right:
return [array[left]]
mid = left + int((right - left) / 2)
leftPart = self.mergeRecursion(array, left, mid)
rightPart = self.mergeRecursion(array, mid + 1, right)
return self.merge(leftPart, rightPart)
def merge(self, leftPart, rightPart):
leftIndex = 0
rightIndex = 0
newArray = []
while leftIndex < len(leftPart) and rightIndex < len(rightPart):
if leftPart[leftIndex] > rightPart[rightIndex]:
newArray.append(rightPart[rightIndex])
rightIndex += 1
else:
newArray.append(leftPart[leftIndex])
leftIndex += 1
while leftIndex < len(leftPart):
newArray.append(leftPart[leftIndex])
leftIndex += 1
while rightIndex < len(rightPart):
newArray.append(rightPart[rightIndex])
rightIndex += 1
return newArray
# print(Solution().mergeSort([3, 5, 1, 2, 4, 8]))
# BlackJackSimulationSystem
from enum import IntEnum
from enum import Enum
class Face(IntEnum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
TEN = 10
JACK = 11
QUEEN = 12
KING = 13
def __init__(self, value):
self.face_val = value
class Suit(Enum):
HEARTS = "Hearts"
CLUBS = "Clubs"
DIAMONDS = "Diamonds"
SPADES = "Spades"
def __init__(self, suit_text):
self.suit_text = suit_text
class Card(object):
def __init__(self, suit_text, value):
# Suit.__init__(suit_text)
# Face.__init__(value)
self.face = value
self.suit = suit_text
class Hand(object):
def __init__(self, name = "PlayerDefault1"):
self.cards = []
self.palyer_name = name
def add_cards(self, card):
self.cards.append(card)
def size(self):
return len(self.cards)
def score(self):
score = 0
for card in self.cards:
score += card.value
return score
cur_hand = Hand()
for face in Face:
for suit in Suit:
# print(face.value, " of ", suit.value)
cur_hand.add_cards(Card(suit.value, face.value))
print(cur_hand.size())
# MergeSort Better space complexity method
class Solution(object):
def mergeSort(self, array=None):
if not array:
return array
dummy = copy.deepcopy(array)
self.helper(array, dummy, 0, len(array) - 1)
return array
def helper(self, array, dummy, left, right):
if left >= right:
return
mid = left + int((right - left) / 2)
self.helper(array, dummy, left, mid)
self.helper(array, dummy, mid + 1, right)
self.merge(array, dummy, left, mid, right)
return
def merge(self, array, dummy, left, mid, right):
if left == right:
return
for index in range (left, right + 1):
dummy[index] = array[index]
i = left
j = mid + 1
arrayIndex = left
while i <= mid and j <= right:
if dummy[i] <= dummy[j]:
array[arrayIndex] = dummy[i]
arrayIndex += 1
i += 1
else:
array[arrayIndex] = dummy[j]
arrayIndex += 1
j += 1
while i <= mid:
array[arrayIndex] = dummy[i]
arrayIndex += 1
i += 1
return
# Test cases
print(Solution().mergeSort([1, 3, 5, 76, 4, 2, -6, 8, 10]))
print(Solution().mergeSort([10, 9, 4, 7, 3, -1, 3, 5]))
print(Solution().mergeSort([1]))
print(Solution().mergeSort([]))
print(Solution().mergeSort())
|
21a14ace6585cd35bc44035e4e0680bc35d2ceee | thepiyushmalhotra/Introduction-to-Pandas | /8statsoperation.py | 832 | 3.546875 | 4 | import pandas as pd
import numpy as np
d={'Name':pd.Series(['Akshay','Rajat','Robin','Kapil','James','Cyril']),'Age':pd.Series([25,26,29,27,23,21]),'Rating':pd.Series([4.23,2.35,1.56,3.20,4.62,3.99])}
df=pd.DataFrame(d)
print df
#print "Sum of All the Data Frame",df.sum()
#print "Sum of All the Age",df['Age'].sum()
print "Sum of All the Age",df['Age'].mean()
print "Sum of All the Age",df['Age'].std()
print "Sum of All the Age",df['Age'].count()
print "Sum of All the Age",df['Age'].min()
print "Sum of All the Age",df['Age'].max()
print "Sum of All the Age",df['Age'].prod()
print "Sum of All the Age",df['Age'].median()
print "Sum of All the Age",df['Age'].cumsum()
print "Sum of All the Age",df['Age'].cumprod()
#print "\nHead\n",df.head(2)
#print "\nTail\n",df.tail(2)
#print df.shape
#print df.T #Transpose of Data Frame
|
4b290f20b1b41c24a8342b5d25e5c94c8a371afe | kyledhebert/PyZombie | /tests.py | 1,439 | 4.03125 | 4 | import unittest
import dice, dice_cup, game, menu, player
class DiceCupTest(unittest.TestCase):
"""Tests for the dice_cup module"""
def setUp(self):
self.cup = dice_cup.DiceCup()
def test_for_six_green_die(self):
self.assertTrue(self.cup.number_of_green_dice == 6)
def test_for_four_yellow_die(self):
self.assertTrue(self.cup.number_of_yellow_dice == 4)
def test_for_three_red_dice(self):
self.assertTrue(self.cup.number_of_red_dice == 3)
class PlayerTest(unittest.TestCase):
"""Tests for the player module"""
def setUp(self):
self.cup = dice_cup.DiceCup()
self.player = player.Player()
self.player.add_dice_to_hand(self.cup)
def test_for_three_dice_in_player_hand(self):
self.assertTrue(len(self.player.hand) == 3)
"""
The GameTest don't run currently, since creating
a Game() instance actually launches the game, and
expects user input.
TODO: seperate creation of a game object and
playing the game
"""
# class GameTest(unittest.TestCase):
# """Tests for the game module"""
# def setUp(self):
# self.game = game.Game()
# self.player = player.Player()
# self.computer = player.Player()
# self.player.turn_score = 3
# self.computer.turn_score = 3
# def test_scores_are_reset_at_start_of_round(self):
# self.game.start_round()
# self.assertTrue(self.player.turn_score == 0)
# self.assertTrue(self.computer.turn_score == 0)
if __name__ == '__main__':
unittest.main() |
5c2a87d2df4e3d71aa260ac9203a788eab34bc2c | sajidazhar/Python_Learning | /odd_even.py | 99 | 3.8125 | 4 | def odd_even(num):
if num%2==0:
return "even"
return "odd"
print(odd_even(9)) |
b1d24de483e6257e3f503a2bb38c01b7a0026e38 | JonathanNakandala/advent-2020 | /02_1.py | 605 | 3.859375 | 4 | def check_password(min, max, letter, password):
letter_count = password.count(letter)
if min <= letter_count <= max:
return 1
return 0
data_file = open("data/data_02.txt", "r")
lines = data_file.readlines()
valid_passwords = 0
for line in lines:
split_space = line.split(" ")
bounds = split_space[0].split("-")
min = int(bounds[0])
max = int(bounds[1])
letter = split_space[1].split(":")[0]
password = split_space[2]
validity = check_password(min, max, letter, password)
valid_passwords = valid_passwords + validity
print(valid_passwords)
|
41b8a35c5311c10f292a99c2ef0c63c9c5713fa9 | iweyy/WIA2004-Operating-Systems | /Lab 7/file sequential.py | 1,478 | 3.796875 | 4 | maximum = 50
files = [0]*maximum
repeat = 1
while repeat == 1:
start = int(input (f"Enter the starting block of the files (0-{maximum-1}): "))
while start<0 or start>=maximum:
if start>=maximum:
print ("Exceed maximum number of file")
if start<0:
print ("Cannot be a negative number")
start = int(input ("Enter the starting block of the files: "))
length = int(input ("Enter the length of the files: "))
while length<0 or length+start>maximum:
if length+start>maximum:
print ("Exceed maximum number of file")
if length<0:
print ("Cannot be less of equal; to 0")
length = int(input ("Enter the length of the files: "))
count = 0
for i in range (length):
if files[start+i] == 0:
count += 1
if count == length:
for i in range (length):
files[start+i] = 1
print (f"files[{start+i}] = 1")
print("The file is allocated to the disk")
else:
print("The file is not allocated to the disk")
repeat = 3
while repeat == 3:
ans = input("Do you want to enter more files? (Yes/No): ")
if (ans.lower() == "yes"):
repeat = 1
elif (ans.lower() == "no"):
repeat = 0
else:
print("Invalid answer.")
repeat = 3
print("Files Allocated are :")
for i in range (maximum):
print (f"files[{i}] = {files[i]}") |
e6fcf0bd9f21caeacd69ec3e5e80467674d323f7 | ChangxingJiang/LeetCode | /1501-1600/1510/1510_Python_2.py | 1,440 | 3.59375 | 4 | # 贪心算法 动态规划 记忆化递归
# O(N×M) M为N开根号
class Solution:
# 动态规划
def __init__(self):
# 计算范围内的完全平方数
# O(logN)
self.square_list = []
now = 1
while True:
square = now ** 2
if square <= 10 ** 5:
self.square_list.append(square)
now += 1
else:
break
self.square_set = set(self.square_list)
def winnerSquareGame(self, n: int) -> bool:
# 定义状态表格
dp = [False] * n
for i in range(n):
num = i + 1
# 如果n为平方数,先手方获胜
if num in self.square_set:
dp[i] = True
# 如果不是平方数,判断先手方是否有必胜策略
else:
dp[i] = not all([dp[num - square - 1] for square in self.square_list if square < num])
# print(dp)
return dp[-1]
if __name__ == "__main__":
print(Solution().winnerSquareGame(1)) # True
print(Solution().winnerSquareGame(2)) # False
print(Solution().winnerSquareGame(3)) # True
print(Solution().winnerSquareGame(4)) # True
print(Solution().winnerSquareGame(7)) # False
print(Solution().winnerSquareGame(17)) # False
print(Solution().winnerSquareGame(47)) # True
print(Solution().winnerSquareGame(74497)) # False
|
5c876fb5d5214c71aaf327c7dc4330c760cdb156 | KaustabRoyChoudhury/Student-Alarm-Clock | /Alam.py | 2,671 | 3.8125 | 4 | import datetime
import winsound
import sys
from win32com.client import Dispatch
import time
hour = input("Enter hour : ")
min1 = input("Enter Minute : ")
sec = input("Enter sec : ")
shift = str(input("Enter AM/PM : "))
date_=0
flag = 0
want = input("Want to Set a Date (Y/N) :")
if want == "Y" or want == "y":
day = input("Enter Day : ")
month = input("Enter month : ")
year = input("Enter year : ")
year = str(int(year)+2000)
if int(day)<10:
day = "0"+day
if int(month)<10:
month = "0"+month
date_ = f"{day}/{month}/{year}"
elif want == "N" or want == "n":
date_=datetime.datetime.now().strftime("%d/%m/%Y")
else:
print("wrong Input!")
sys.exit()
if int(hour)>12:
print("Error! Hour is 12 Format !")
sys.exit()
if int(min1)>=60:
if int(min1) == 60:
min1 = "0"
else:
print("Error! Minute Wrong !")
sys.exit()
if int(sec)>=60:
if int(sec) == 60:
sec = "0"
else:
print("Error! Second Wrong !")
sys.exit()
if int(hour) <10:
hour = "0"+hour
if int(min1) < 10:
min1 = "0"+min1
if int(sec) <10:
sec = "0"+sec
if shift == "am" or shift == "AM" :
if int(hour) == 12:
hour = "00"
# else:
elif shift == "pm" or shift == "PM":
hour = str(int(hour) + 12)
else:
print("Wrong Input")
sys.exit()
data = f"{hour}:{min1}:{sec}"
remind = input("Want to Set Remainder (Y/N): ")
if remind == "Y" or remind == "y":
input_remainder = input("Enter Reminder : ")
with open("reminder.txt","w+") as f:
f.write("Your Remainder is : '"+input_remainder +"'"+"\nand You set the Time : "+data + "\nand Date : "+date_)
f.close()
flag = 1
else:
pass
voice = ""
sound=Dispatch("SAPI.Spvoice")
print(f"Alam Time is : {data}:{shift} \nDate is : {date_}")
if flag == 1:
print("Remainder Set!!!")
with open("reminder.txt","r") as f:
voice = f.read()
f.close()
else:
print("Remainder Not Set!!!!")
music_dir = "snd\sound.wav"
while True:
current_time = datetime.datetime.now()
now = current_time.strftime("%H:%M:%S")
date = current_time.strftime("%d/%m/%Y")
if now == data and date == date_:
print("Wake Up")
winsound.PlaySound(music_dir, winsound.SND_ALIAS )
time.sleep(10)
winsound.PlaySound(None, winsound.SND_ASYNC)
with open ("reminder.txt","r") as f:
a = f.read()
sound.Speak(voice)
print("Sir I want To Remind You that : ",a)
break
|
bc231fa3c23e541ac067e3ce4460bce96b2cfa26 | kgashok/rps-ai | /src/database.py | 2,454 | 3.546875 | 4 | import psycopg2
import pandas as pd
from src.config import config
import datetime as datetime
import time
# returns a given SQL SELECT query to a pandas DataFrame object
def query_to_df(query= "SELECT * FROM power_weather LIMIT 15"):
params=config()
try:
conn = psycopg2.connect(**params)
cursor = conn.cursor()
cursor.execute(query)
df = pd.DataFrame(cursor.fetchall())
print(cursor.description)
df.columns = [i[0] for i in cursor.description]
#df.set_index('id', drop=True, inplace=True)
print('df Created')
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL:", error)
if(conn):
cursor.close()
conn.close()
return df
#executes a given SQL query in the postgresql database
def execute_query(query):
params=config()
try:
conn = psycopg2.connect(**params)
cursor = conn.cursor()
cursor.execute(query)
print("Query Executed")
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL:", error)
if(conn):
conn.commit()
cursor.close()
conn.close()
#creates a new database from given df
def df_to_sql(df, name):
params=config()
try:
engine = create_engine(**params)
df.to_sql(name, engine)
print("Database Created")
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL:", error)
def update_sql_from_df(df, name):
params=config()
try:
conn = psycopg2.connect(**params)
cursor = conn.cursor()
for index, row in df.iterrows():
update_query = f"INSERT INTO {name} VALUES ({row.game_id}, {row.name}, {row.p1}, {row.p2}, {row.winner}, {row.model_choice}, {row.model0}, {row.model1}, {row.model2}, {row.model3}, {row.model4}, {row.model5}, '{row.timestamp if type(row.timestamp) != int else datetime.datetime.fromtimestamp(int(str(row.timestamp)[:10]))}', '{row.ip_address}')"
cursor.execute(update_query, name)
print("Database Updated")
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL:", error)
finally:
if(conn):
conn.commit()
cursor.close()
conn.close() |
d173932243169a2e26cee3feeb07900e735583d9 | Astitwa-Agarwal/tathastu_week_of_code | /day1/program4.py | 264 | 3.609375 | 4 | cp,sp = map(int,input('Enter cost price and selling price: ').split())
if(sp>=cp):
profit = sp-cp
print('Profit is: ',profit)
n = int(input('Enter the percentage of profit you wanna increase: '))
sp = sp+ (n*cp)/100
print('The new selling price is:', sp)
|
822dd30cb07c9c09cbd422bb9b7dcb973932d4ad | JohnyTheLittle/pythonSciPlay | /systems_of_equations.py | 251 | 3.515625 | 4 | import numpy as np
from numpy import linalg
"""
3x1-2x2+x3=7
x1+x2-2x3=-4
-3x1-2x2+x3=1
"""
A = np.array([[3, -2, 1], [1, 1, -2], [-3, -2, 1]])
b = np.array([7, -4, 1])
x = linalg.solve(A, b)
print(A)
print(b)
print(x)
print("-------")
print(A@x)
|
53a4c8a72f8e33b5eb89e03d4e5faf7917db3806 | UtsavRaychaudhuri/leetcode | /lc-24.py | 952 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPair(self,head,returnthishead,chainthishead):
if head is None:
return returnthishead.next
prev=head
head=head.next
if head is None:
chainthishead.next=ListNode(prev.val)
chainthishead=chainthishead.next
return returnthishead.next
chainthishead.next=ListNode(head.val)
chainthishead=chainthishead.next
chainthishead.next=ListNode(prev.val)
chainthishead=chainthishead.next
return self.swapPair(head.next,returnthishead,chainthishead)
def swapPairs(self,head):
chainthishead=ListNode(0)
returnthishead=chainthishead
return self.swapPair(head,returnthishead,chainthishead)
|
db37a86469bcdec5e4b1415053896450337845b0 | decadevs/using-sqlalchemy-folly77folly | /storage/reader_storage.py | 457 | 3.671875 | 4 | from abc import ABC, abstractmethod
class Storage(ABC):
def __init__(self,*kwargs):
self.id = bookid
self.booktitle = booktitle
self.bookauthor = bookauthor
@abstractmethod
def create(self, **kwargs):
pass
@abstractmethod
def fetch(self, **kwargs):
pass
@abstractmethod
def delete(self, **kwargs):
pass
@abstractmethod
def fetch_all(self):
pass
|
50b11f3566fdab14eb813da511da2c17a0617f02 | matthowe/8queens | /eightQueens.py | 2,596 | 3.953125 | 4 |
def createBoard():
board = [["." for _ in range(8)] for _ in range(8)]
return board
def displayBoard(board):
for y in range(8):
for x in range(8):
print(board[y][x],end='')
print()
print()
def autoPlaceQueen(board):
for y in range(8):
for x in range(8):
if board[y][x] == ".":
board[y][x] = "Q"
queenBlocks(board)
return True
return False
def placeQueen(board,y,x):
if board[y][x] == ".":
board[y][x] = "Q"
queenBlocks(board)
return True
return False
def queenBlocks(board):
"""for x and y"""
for y in range(8):
for x in range(8):
if board[y][x] == "Q":
for xn in range(8):
if board[y][xn] == ".":
board[y][xn] = "X"
for yn in range(8):
if board[yn][x] == ".":
board[yn][x] = "X"
"""diagonal y+x+"""
yn = y
for xn in range(x,8):
if board[yn][xn] == ".":
board[yn][xn] = "X"
if yn < 7:
yn=yn+1
"""diagonal y+x-"""
yn = y
for xn in range(x,-1,-1):
if board[yn][xn] == ".":
board[yn][xn] = "X"
if yn < 7:
yn=yn+1
"""diagonal y-x+"""
xn = x
for yn in range(y,-1,-1):
if board[yn][xn] == ".":
board[yn][xn] = "X"
if xn < 7:
xn=xn+1
"""diagonal y-x-"""
xn = x
for yn in range(y,-1,-1):
if board[yn][xn] == ".":
board[yn][xn] = "X"
if xn > -1:
xn=xn-1
def isBoardFull(board):
for y in range(8):
for x in range(8):
if board[y][x] == ".":
return False
#print("board full")
return True
def freeSpaces(board):
freeSquares=[]
for y in range(8):
for x in range(8):
if board[y][x] == ".":
freeSquares.append([y,x])
return freeSquares
|
6d604dfd46c22f5782f75127a784a5d578196643 | S1L1C0N1/Module-5 | /loopy_loops.py | 882 | 4.03125 | 4 | def func():
pokemon = ("picachu", "charmander", "bulbasaur")
print(pokemon[0])
print("done")
(starter1, starter2, starter3) = pokemon
print(starter2)
print("done")
tuple = ("J", "A", "C", "K")
print(f"Is i in tuple: {'i' in tuple}")
print("done")
for x in range(2, 11):
x += 0
print (x)
print("done")
x = 2
while x < 11:
print(x)
x += 1
print("done")
stringy = "This is a simple string"
x = 0
for x in range(len(stringy)):
print(stringy[x])
x += 1
print("done")
setty = ('this', 'is', 'a', 'simple', 'set')
index = 0
times = 0
for index in range(len(setty)):
times = 0
while times < 3:
print(setty[index])
times += 1
index += 1
print("done")
if __name__ == "__main__":
func() |
c537a6e4722dd1dc7924264bfeac243791e42cab | ptaushanov/SoftuniPythonProgrammingBasics | /SimpleConditions/07.sumSeconds.py | 178 | 3.75 | 4 | first = int(input())
second = int(input())
third = int(input())
sec_sum = first + second + third
hours = sec_sum / 60
seconds = sec_sum % 60
print("%d:%02d" % (hours, seconds)) |
85e39259a786748820457862ec8ee26166248fb2 | andri-x99/praxis-academy | /novice/01-03/latihan/classinstance.py | 217 | 3.578125 | 4 | class Dog:
kind='canine'
def __init__(self,name):
self.name = name
d=Dog('Johny')
# print(d)
e=Dog('Zranc')
# print(e)
f=Dog('Diza')
# print(f)
print(d.kind)
print(d.name)
print(e.name)
print(f.name) |
800c7d600a190a174a6a99a4e7f4bde7f63f515b | heidamn/python_hometasks | /homework03/life_with_classes.py | 6,206 | 3.890625 | 4 | """ Лабораторная работа №3
Игра Жизнь с использованием классов
Шоломов Даниил, k3140
ИТМО, 2018
"""
import random
from copy import deepcopy
import pygame
from pygame.locals import *
class GameOfLife:
"""класс визуализации и процесса игры"""
def __init__(self, width: int = 640, height: int = 480, cell_size: int = 10, speed: int = 10) -> None:
self.width = width
self.height = height
self.cell_size = cell_size
# Устанавливаем размер окна
self.screen_size = width, height
# Создание нового окна
self.screen = pygame.display.set_mode(self.screen_size)
# Вычисляем количество ячеек по вертикали и горизонтали
self.cell_width = self.width // self.cell_size
self.cell_height = self.height // self.cell_size
# Скорость протекания игры
self.speed = speed
def draw_grid(self) -> None:
""" Отрисовать сетку """
for x in range(0, self.width, self.cell_size):
pygame.draw.line(self.screen, pygame.Color('black'),
(x, 0), (x, self.height))
for y in range(0, self.height, self.cell_size):
pygame.draw.line(self.screen, pygame.Color('black'),
(0, y), (self.width, y))
def draw_cell_list(self, celllist) -> None:
""" Отображение списка клеток
:param rects: Список клеток для отрисовки, представленный в виде матрицы
"""
for rown, row in enumerate(celllist.clist):
for coln, col in enumerate(row):
if col.is_alive():
pygame.draw.rect(self.screen, pygame.Color('green'),
(rown * self.cell_size, coln * self.cell_size, self.cell_size, self.cell_size))
else:
pygame.draw.rect(self.screen, pygame.Color('white'),
(rown * self.cell_size, coln * self.cell_size, self.cell_size, self.cell_size))
def run(self) -> None:
""" Запустить игру """
pygame.init()
clock = pygame.time.Clock()
pygame.display.set_caption('Game of Life')
self.screen.fill(pygame.Color('white'))
celllist = CellList(self.cell_width, self.cell_height, randomize=True)
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
self.draw_cell_list(celllist)
self.draw_grid()
celllist.update()
pygame.display.flip()
clock.tick(self.speed)
pygame.quit()
class Cell:
"""Класс, описывающий отдельную клетку поля """
def __init__(self, row: int, col: int, state: bool = False) -> None:
self.row = row
self.col = col
self.state = state
def is_alive(self) -> bool:
""" Проверка статуса клетки"""
return self.state
class CellList:
""" Класс игрового поля, состоящего из клеток"""
def __init__(self, nrows: int, ncols: int, randomize: bool = False) -> None:
self.nrows = nrows
self.ncols = ncols
self.randomize = randomize
if randomize:
clist = [[Cell(rown, coln, state=bool(random.randint(0, 1))) for coln in range(ncols)] for rown in range(nrows)]
else:
clist = [[Cell(rown, coln, state=False) for coln in range(ncols)] for rown in range(nrows)]
self.clist = clist
def get_neighbours(self, cell: Cell) -> list:
""" Получение состояния соседних клеток """
return [self.clist[rown + cell.row][coln + cell.col] for rown in range(-1, 2) for coln in range(-1, 2) if (coln or rown) and 0 <= cell.row + rown < self.nrows and 0 <= cell.col + coln < self.ncols]
def update(self) -> object:
""" Обновление игрового поля """
new_clist = deepcopy(self.clist)
for cell in self:
neighbours = self.get_neighbours(cell)
neighbours_num = 0
for neighbour in neighbours:
if neighbour.is_alive():
neighbours_num += 1
if (neighbours_num == 2 and cell.is_alive()) or neighbours_num == 3:
new_clist[cell.row][cell.col] = Cell(cell.row, cell.col, state=True)
else:
new_clist[cell.row][cell.col] = Cell(cell.row, cell.col, state=False)
self.clist = new_clist
return self
@classmethod
def from_file(cls, filename: str) -> object:
""" Получение поля из файла """
with open(filename, 'r') as cells_file:
cells_str = cells_file.read()
nrows = cells_str.count('\n')
cells = [bool(int(c)) for c in cells_str if c in '01']
ncols = len(cells) // nrows
grid = CellList(nrows, ncols)
count = 0
for cell in grid:
cell.state = cells[count]
count += 1
return grid
def __iter__(self):
self.row_count, self.col_count = 0, 0
return self
def __next__(self):
if self.row_count == self.nrows:
raise StopIteration
cell = self.clist[self.row_count][self.col_count]
self.col_count += 1
if self.col_count == self.ncols:
self.col_count = 0
self.row_count += 1
return cell
def __str__(self):
strclist = ''
for cell in self:
if cell.is_alive():
strclist += '1 '
else:
strclist += '0 '
if cell.col == self.ncols - 1:
strclist += '\n'
return strclist
if __name__ == '__main__':
game = GameOfLife(800, 600, 20)
game.run()
|
17fb34e2416a346508a1dc336ea63107f8175aec | solankeganesh777/Python-Basics-for-data-science-project | /Other/Inheritance.py | 1,035 | 4.1875 | 4 | #Python Inheritance
#Parent class/Base class
class Cars:
def __init__(self,brand,model):
self.brand=brand
self.model=model
def printCarDetails(self):
print(self.brand)
print(self.model)
car1=Cars('RR',"Discovery")
car1.printCarDetails()
#Child class/Derived class
class SUV(Cars):
pass
car2=SUV('Jaguar','xj')
car2.printCarDetails()
print("\n")
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("Ganesh", "Solanke")
x.printname()
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mangesh", "Solanke", 2019)
x.welcome()
x.printname()
|
be696afca26b3e0f8ed3cdcf75240474de5528ca | HJ3EQG/misionTicFundamentosPython | /reto3.py | 14,676 | 3.828125 | 4 | #Bienvenidos Tripulantes Grupo 72, adjunte aqui el codigo del Reto 3, para su evaluación
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 17:02:28 2021
@author: david
"""
import time
import datetime
from datetime import date, datetime, time, timedelta
contador = 1
contador1 = 1
compras = list()
compras2 = list()
datos_clientes = list()
datos_envio = list()
i = 0
j = 0
k = 0
l = 0
def datos_cliente():
opt = 99
global datos_clientes
global j
while opt != 2:
datos_clientes.append([])
#print("Tipo de documento: ")
tipo_doc = str(input("> "))
datos_clientes[j].append(tipo_doc)
#print("Numero de documento: ")
num_doc = str(input("> "))
datos_clientes[j].append(num_doc)
#print("Nombre cliente:")
nombre_cliente = str(input("> "))
datos_clientes[j].append(nombre_cliente)
#print("Direccion:")
dir_cliente = str(input("> "))
datos_clientes[j].append(dir_cliente)
#print("Teléfono:")
num_tel = str(input("> "))
datos_clientes[j].append(num_tel)
#print("Ciudad:")
ciudad = str(input("> "))
datos_clientes[j].append(ciudad)
#print("País:")
ciudad = str(input("> "))
datos_clientes[j].append(ciudad)
#print("otro cliente?(1=Si; 2=No)")
opt = int(input("> "))
j += 1
print(len(datos_clientes))
def input_datos_envio():
opt = 99
global l
global datos_envio
while opt != 2:
datos_envio.append([])
#print("Tipo de documento destinatario: ")
tipo_d = str(input("> "))
datos_envio[l].append(tipo_d)
#print("Numero de documento: ")
num_d = str(input("> "))
datos_envio[l].append(num_d)
#print("Nombre destinatario: ")
nombre_d = str(input("> "))
datos_envio[l].append(nombre_d)
#print("Direccion destinatario: ")
direccion_d = str(input("> "))
datos_envio[l].append(direccion_d)
#print("Telefono: ")
tel_d = str(input("> "))
datos_envio[l].append(tel_d)
#print("Ciudad destino: ")
ciudad_d = str(input("> "))
datos_envio[l].append(ciudad_d)
#print("País destino: ")
pais_d = str(input("> "))
datos_envio[l].append(pais_d)
#print("Empresa transportadora: ")
trans_d = str(input("> "))
datos_envio[l].append(trans_d)
#print("otro cliente?(1=Si; 2=No)")
opt = int(input("> "))
l += 1
print(len(datos_envio))
def calculo_total_compras():
choice = 99
while choice!=3:
#print("Seleccione (1=Turno 1, 2=Turno 2, 3=Salir)")
#try:
choice = int(input("> "))
if choice == 1:
if len(compras) > 0:
total_compras = sum([compra[-1] for compra in compras])
print(int(total_compras))
else:
print(0)
elif choice == 2:
if len(compras2) > 0:
total_compras = sum([compra[-1] for compra in compras2])
print(int(total_compras))
else:
print(0)
elif choice == 3:
continue
else:
continue
def calculo_turno_1(forma, tipo):
global contador
global compras
global i
op2 = 88
opb = 89
subtotal = 0
descuento_cant = 0
valor_compra = 0
total = 0
while opb != 2:
hoy= datetime.now()
#print(hoy.time())
formatdate= "%d/%m/%Y %H:%M:%S"
now = hoy.strftime(formatdate)
compras.append([])
compras[i].append(contador)
compras[i].append(now.split()[0])
compras[i].append(now.split()[1])
compras[i].append(forma)
compras[i].append(tipo)
while(op2!=2):
#print("Ingrese la referencia del producto: ")
referencia_p = str(input("> "))
compras[i].append(referencia_p)
#print("Ingrese nombre del producto: ")
nombre_p = str(input("> "))
compras[i].append(nombre_p)
#print("Ingrese cantidad de producto: ")
cantidad_p = int(input("> "))
compras[i].append(cantidad_p)
#print("Ingrese precio del producto: ")
precio_p = int(input("> "))
compras[i].append(precio_p)
if cantidad_p > 3:
descuento_cant += cantidad_p * precio_p * 0.05
subtotal += cantidad_p * precio_p
valor_compra = subtotal - descuento_cant
else:
descuento_cant += 0
subtotal += cantidad_p * precio_p
valor_compra = subtotal
if forma == 1:
if tipo == 1:
if valor_compra > 800000:
envio = 0
dscto_envio = 8000
else:
envio = 8000
dscto_envio = 0
if tipo == 2:
envio = 10000
dscto_envio = 0
if tipo == 3:
envio = 40000
dscto_envio = 0
elif forma == 2:
if tipo == 1:
if valor_compra > 500000:
envio = 0
dscto_envio = 4000
else:
envio = 4000
dscto_envio = 0
if tipo == 2:
if valor_compra >= 1000000:
envio = 0
dscto_envio = 5000
else:
envio = 5000
dscto_envio = 0
if tipo == 3:
if valor_compra >= 2000000:
envio = 0
dscto_envio = 20000
else:
envio = 20000
dscto_envio = 0
#print("Otro producto? (1=Si ; 2=No)")
compras[i].append(int(subtotal))
compras[i].append(int(descuento_cant))
compras[i].append(int(envio))
total = subtotal + envio - descuento_cant
compras[i].append(int(total))
op2 = int(input("> "))
#print(compras)
print(int(subtotal)) #Valor compra
print(int(descuento_cant)) # Valor descuento
print(int(envio))# Valor envio
print(int(total)) # Valor total a pagar
#print("Otra compra:")
opb = int(input("> "))
contador += 1
i += 1
subtotal = 0
descuento_cant = 0
valor_compra = 0
total = 0
op2 = 33
def calculo_turno_2(forma, tipo):
global contador1
global compras2
global k
op2 = 88
opb = 89
subtotal = 0
descuento_cant = 0
valor_compra = 0
total = 0
while opb != 2:
hoy= datetime.now()
#print(hoy.time())
formatdate= "%d/%m/%Y %H:%M:%S"
now = hoy.strftime(formatdate)
compras2.append([])
compras2[k].append(contador1)
compras2[k].append(now.split()[0])
compras2[k].append(now.split()[1])
compras2[k].append(forma)
compras2[k].append(tipo)
while(op2!=2):
#print("Ingrese la referencia del producto: ")
referencia_p = str(input("> "))
compras2[k].append(referencia_p)
#print("Ingrese nombre del producto: ")
nombre_p = str(input("> "))
compras2[k].append(nombre_p)
#print("Ingrese cantidad de producto: ")
cantidad_p = int(input("> "))
compras2[k].append(cantidad_p)
#print("Ingrese precio del producto: ")
precio_p = int(input("> "))
compras2[k].append(precio_p)
if cantidad_p > 3:
descuento_cant += cantidad_p * precio_p * 0.05
subtotal += cantidad_p * precio_p
valor_compra = subtotal - descuento_cant
else:
descuento_cant += 0
subtotal += cantidad_p * precio_p
valor_compra = subtotal
if forma == 1:
if tipo == 1:
if valor_compra > 800000:
envio = 0
dscto_envio = 8000
else:
envio = 8000
dscto_envio = 0
if tipo == 2:
envio = 10000
dscto_envio = 0
if tipo == 3:
envio = 40000
dscto_envio = 0
elif forma == 2:
if tipo == 1:
if valor_compra > 500000:
envio = 0
dscto_envio = 4000
else:
envio = 4000
dscto_envio = 0
if tipo == 2:
if valor_compra >= 1000000:
envio = 0
dscto_envio = 5000
else:
envio = 5000
dscto_envio = 0
if tipo == 3:
if valor_compra >= 2000000:
envio = 0
dscto_envio = 20000
else:
envio = 20000
dscto_envio = 0
#print("Otro producto? (1=Si ; 2=No)")
compras2[k].append(int(subtotal))
compras2[k].append(int(descuento_cant))
compras2[k].append(int(envio))
total = subtotal + envio - descuento_cant
compras2[k].append(int(total))
op2 = int(input("> "))
#print(compras2)
print(int(subtotal)) #Valor compra
print(int(descuento_cant)) # Valor descuento
print(int(envio))# Valor envio
print(int(total)) # Valor total a pagar
#print("Otra compra:")
opb = int(input("> "))
contador1 += 1
k += 1
subtotal = 0
descuento_cant = 0
valor_compra = 0
total = 0
op2 = 33
def cantidad_compras_turno():
choice = 99
while choice!=3:
#print("Seleccione (1=Turno 1, 2=Turno 2, 3=Salir)")
#try:
choice = int(input("> "))
if choice == 1:
print(len(compras))
elif choice == 2:
print(len(compras2))
elif choice == 3:
continue
else:
continue
#except:
# continue
def main():
medio_dia = time(12,0,0,0)
opcion = 99
while(opcion != 6):
hoy = datetime.now()
hora_actual = hoy.time()
#print(hora_actual < medio_dia)
if hora_actual < medio_dia:
#print(" TURNO 1 ".center(60,'-'))
#try:
#print("Menú de Opciones\n1.Ingreso Datos del cliente\n2.Ingreso Datos para cálculo de la compra e impresión resumen de la compra\n3.Impresion Cantidad de compras por turno\n4.Impresion valor compras por turno\n5.Datos del envío\n6.Salir")
opcion=int(input("> "))
if opcion == 1:
datos_cliente()
elif opcion == 2:
#print("Ingrese la forma me envío: 1= Rápido 2=Normal")
forma_envio=int(input("> "))
if forma_envio >= 1: # Rápido
#print("Ingrese la forma me envío: 1=Local, 2=Nacional, 3=Internacional")
tipo_envio=int(input("> "))
#print(tipo_envio)
if tipo_envio >= 1 and tipo_envio <=3:
calculo_turno_1(forma_envio, tipo_envio)
elif forma_envio == 2: # normal
#print("Ingrese la forma me envío: 1=Local, 2=Nacional, 3=Internacional")
tipo_envio=int(input("> "))
#print(tipo_envio)
if tipo_envio >= 1 and tipo_envio <=3:
calculo_turno_1(forma_envio, tipo_envio)
elif opcion == 3:
#print("Cantidad compras por turno")
cantidad_compras_turno()
elif opcion == 4:
#print("Imprimir resumen compras por turno")
calculo_total_compras()
elif opcion == 5:
#print("Pedir datos de envío")
input_datos_envio()
else:
continue
#print("la opcion ingresada no existe")
#except:
# continue
else:
#print(" TURNO 2 ".center(60,'-'))
#try:
#print("Menú de Opciones\n1.Ingreso Datos del cliente\n2.Ingreso Datos para cálculo de la compra e impresión resumen de la compra\n3.Impresion Cantidad de compras por turno\n4.Impresion valor compras por turno\n5.Datos del envío\n6.Salir")
opcion=int(input("> "))
if opcion == 1:
datos_cliente()
elif opcion == 2:
#print("Ingrese la forma me envío: 1= Rápido 2=Normal")
forma_envio=int(input("> "))
if forma_envio >= 1: # Rápido
#print("Ingrese la forma me envío: 1=Local, 2=Nacional, 3=Internacional")
tipo_envio=int(input("> "))
#print(tipo_envio)
if tipo_envio >= 1 and tipo_envio <=3:
calculo_turno_2(forma_envio, tipo_envio)
elif forma_envio == 2: # normal
#print("Ingrese la forma me envío: 1=Local, 2=Nacional, 3=Internacional")
tipo_envio=int(input("> "))
#print(tipo_envio)
if tipo_envio >= 1 and tipo_envio <=3:
calculo_turno_2(forma_envio, tipo_envio)
elif opcion == 3:
#print("Cantidad compras por turno")
cantidad_compras_turno()
elif opcion == 4:
#print("Imprimir resumen compras por turno")
calculo_total_compras()
elif opcion == 5:
#print("Pedir datos de envío")
input_datos_envio()
else:
continue
#print("la opcion ingresada no existe")
#except:
# continue
if __name__ == '__main__':
#cantidad_compras_turno()
main()
#calculo_turno_2(1, 2)
|
6e40ab922f7dd75c9cd5253a87a0555ece19a5d6 | Vishad89/heyjude | /Python/wip/tictactoe.py | 1,885 | 3.90625 | 4 | import random
board = {}
end = False
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def board():
print(' | | ')
#print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | | ')
print('------------------')
print(' | | ')
#print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | | ')
print('------------------')
print(' | | ')
#print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | | ')
def playerletter():
plylt = raw_input("what letter do you want to play with [O or X]: ")
plylt = plylt.upper()
if plylt == "X":
return ['X', 'O' ]
firstmove(plylt)
elif plylt == "O":
return ['O', 'X']
firstmove(plylt)
else:
print "Please select the right option, it has to be from X or O"
playerletter()
def firstmove(plylt):
if random.randint(0,1) == 0:
print "computer's move"
else:
print "your move, you have chosen " + plylt
registermoves(plylt)
def registermoves(plylt):
a = int (raw_input("enter a number from 1 to 9"))
if board[a] == "X" or "O":
print "please enter a new number"
registermoves()
else:
board[a] = plylt
def gamecheck(plylt):
count = 0
for a in win_commbinations:
if board[a[0]] == board[a[1]] == board[a[2]] == plylt:
print("Player 1 Wins!\n")
print("Congratulations!\n")
return True
if board[a[0]] == board[a[1]] == board[a[2]] != plylt:
print("Player 2 Wins!\n")
print("Congratulations!\n")
return True
for a in range(9):
if board[a] == "X" or board[a] == "O":
count += 1
if count == 9:
print("The game ends in a Tie\n")
#playerletter()
|
43a510f678cea4083e67b5204e907c6f7b4b9200 | Kaushiksekar/SDE_Prepration | /Python_Specifics/Inheritance/Static_Methods.py | 328 | 3.59375 | 4 | class Robot:
__counter = 0
def __init__(self):
type(self).__counter += 1 # can also be Robot.self
@staticmethod
def RobotInstances():
return Robot.__counter
print(Robot.RobotInstances())
x = Robot()
print(x.RobotInstances())
y = Robot()
print(x.RobotInstances())
print(Robot.RobotInstances())
|
ef63132f9f06b498275e01e4c8e4870684b0a9f0 | howard5758/graph_search_problem | /AI_1/Lossy_cannibals.py | 1,264 | 3.53125 | 4 | # Author: Ping-Jung Liu
# Date: September 17th 2017
# COSC 76 Assignment 1: Missionaries and Cannibals
# Acknowledgement: Professor Devin Balkom for providing the general structure
from Lossy_CannibalProblem import Lossy_CannibalProblem
from uninformed_search import bfs_search, dfs_search, ids_search
# Create a few test problems:
# the forth element of states indicates the number of eaten missionaries
# which should definitely be 0 at the start_state
# the second parameter indicates the number of missionaries allowed to be eaten
# if set to 0, the results should be the same as the original problems
problem331 = Lossy_CannibalProblem((3, 3, 1, 0), 2)
problem541 = Lossy_CannibalProblem((5, 4, 1, 0), 2)
problem551 = Lossy_CannibalProblem((5, 5, 1, 0), 2)
# Run the searches.
# Each of the search algorithms should return a SearchSolution object,
# even if the goal was not found. If goal not found, len() of the path
# in the solution object should be 0.
print(bfs_search(problem331))
print(dfs_search(problem331))
print(ids_search(problem331))
print(bfs_search(problem551))
print(dfs_search(problem551))
print(ids_search(problem551))
print(bfs_search(problem541))
print(dfs_search(problem541))
print(ids_search(problem541))
#print(dfs_search(problemtest))
|
2a2f1c2d8e67816be819fa73d35847fa82f00636 | GermanChiocchia/EjercitacionUdemyMasterClass | /challenges/challenge7.py | 225 | 4 | 4 | prices = {'Peon':100,'Alfil':250,'Caballo':300,'Reina':900, 'Torre':500}
product = input('Ingrese una pieza para saber su valor')
if product in prices:
print(prices[product],end=' $')
else:
print('Pieza inexistente!') |
c105558c54fe6f9050aae0b5862dd28973a876e2 | IselaFraire/pu_figura | /figura/tests/features/figura.py | 514 | 3.578125 | 4 | class Figura(object):
def __init__(self):
self.resultado = 0
def area_rectangulo(self, base, altura):
self.resultado = base * altura
def area_circulo(self,radius):
self.resultado = round(3.1416 * radius ** 2, 2)
def area_trapecio(self, base_mayor, base_menor, altura):
self.resultado = (base_mayor + base_menor) * altura / 2.0
def area_cuadrado(self, lado):
self.resultado = lado ** 2
def obtener_resultado(self):
return self.resultado
|
212da96e99535779b36e7552082439832e7b1fc5 | xinmiaoo/leetcode_Aug_3 | /0017. Letter Combinations of a Phone Number.py | 1,181 | 3.546875 | 4 | # class Solution(object):
# def letterCombinations(self, digits):
# """
# :type digits: str
# :rtype: List[str]
# """
# lookup={"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno",
# "7":"pqrs","8":"tuv","9":"wxyz"}
# if digits=="":
# return []
# ans=[""]
# for i in digits:
# temp=[]
# for j in ans:
# temp+=[j+x for x in lookup[i]]
# ans=temp
# return ans
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
lookup={"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno",
"7":"pqrs","8":"tuv","9":"wxyz"}
def backtrack(combination,next_digit):
if len(next_digit)==0:
output.append(combination)
else:
for i in lookup[next_digit[0]]:
backtrack(combination+i,next_digit[1:])
output=[]
if digits:
backtrack("",digits)
return output
|
c23e0d9f63ac3a1e33868c1d8e1ef0c921c67923 | zero1hac/cp-practice | /hackerrank/algo/grading.py | 232 | 3.8125 | 4 | N = int(raw_input())
while N:
grade = int(raw_input())
if grade < 38:
print grade
else :
if ((grade/5 +1)*5 - grade) < 3:
print (grade/5 + 1)*5
else:
print grade
N-=1
|
1b8247076341aa631691c5663196772003d29ca2 | DAyurzana/hello-world | /shop.py | 330 | 3.5625 | 4 | #shop.py
def check_money(total_cost, customer_money):
if total_cost < customer_money:
return True
elif customer_money < total_cost:
return False
#This should print False
can_pay = check_money(107, 49)
print(can_pay)
#This should print True
can_pay = check_money(6, 88)
print(can_pay)
|
9bc8788394678649f661da18f3990448f3fdb2d6 | jinjinfan/Principles_of_Computing | /word_wrangler.py | 3,875 | 3.921875 | 4 | """
Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
returned_list =[]
item_ = ""
for item in list1:
if item!= item_:
item_ = item
returned_list.append(item_)
return returned_list
def intersect(list1, list2):
"""
Compute the intersection of two sorted lists.
Returns a new sorted list containing only elements that are in
both list1 and list2.
This function can be iterative.
"""
returned_list = []
idx1 = idx2 = 0
while idx1 < len(list1) and idx2 < len(list2):
if list2[idx2] > list1[idx1]:
idx1 += 1
elif list2[idx2] < list1[idx1]:
idx2 += 1
elif list2[idx2] == list1[idx1]:
returned_list.append(list1[idx1])
idx1 += 1
idx2 += 1
return returned_list
# Functions to perform merge sort
def merge(list1, list2):
"""
Merge two sorted lists.
Returns a new sorted list containing all of the elements that
are in either list1 and list2.
This function can be iterative.
"""
returned_list = []
idx1 = idx2 = 0
while idx1 < len(list1) and idx2 < len(list2):
if list2[idx2] > list1[idx1]:
returned_list.append(list1[idx1])
idx1 += 1
else:
returned_list.append(list2[idx2])
idx2 += 1
if idx1 == len(list1):
for index in range(idx2, len(list2)):
returned_list.append(list2[index])
else:
for index in range(idx1, len(list1)):
returned_list.append(list1[index])
return returned_list
def merge_sort(list1):
"""
Sort the elements of list1.
Return a new sorted list with the same elements as list1.
This function should be recursive.
"""
if list1 == []:
return []
else:
pivot = list1[0]
lesser = [item for item in list1 if item < pivot]
pivots = [item for item in list1 if item == pivot]
greater = [item for item in list1 if item > pivot]
return merge_sort(lesser) + pivots + merge_sort(greater)
# Function to generate all strings for the word wrangler game
def gen_all_strings(word):
"""
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
"""
if len(word) == 0:
return [""]
first = word[0]
rest_strings = gen_all_strings(word[1:])
newstring = list(rest_strings)
for item in rest_strings:
newstring.append(first + item)
for index in range(len(item)-1):
newstring.append(item[:index+1] + first + item[index+1:])
if item != "":
newstring.append(item + first)
return newstring
# Function to load words from a file
def load_words(filename):
"""
Load word list from the file named filename.
Returns a list of strings.
"""
url = codeskulptor.file2url(filename)
netfile = urllib2.urlopen(url)
string_lists = []
for line in netfile.readlines():
string_lists.append(line[:-1])
return string_lists
def run():
"""
Run game.
"""
words = load_words(WORDFILE)
wrangler = provided.WordWrangler(words, remove_duplicates,
intersect, merge_sort,
gen_all_strings)
provided.run_game(wrangler)
# Uncomment when you are ready to try the game
run() |
dd13fc460c04701470f90b07a5dc69336265861e | leithdm/python-proj | /projects/day-25/initial.py | 4,349 | 4.34375 | 4 | import csv
import pandas
from statistics import mean
# 1. using 'import csv' - a basic in-built way to work with csv data
with open("weather_data.csv") as data_file:
data = csv.reader(data_file)
temperatures = []
for row in data:
# do not include 'temp' text from the first row
if row[1] != "temp":
temperatures.append(int(row[1]))
print(temperatures)
# 2. using 'import pandas'.
# Whenever there is a csv file....best to use pandas
# Pandas Documentation: https://pandas.pydata.org/docs/
# Pandas API ref: https://pandas.pydata.org/docs/reference/index.html
# well formatted data
data = pandas.read_csv("weather_data.csv")
print(data)
print(data['temp'])
# 2 primary data structures - Series (1-dimensional, like a single excel column),
# and DataFrame (2-dimensional, like the whole table)
# determine what the panda 'type' is of data and data["temp"]
print(type(data))
print(type(data["temp"]))
# convert a panda Dataframe to a dictionary [note: check the API ref]
print(data.to_dict())
# convert a panda Series to a list
print(data["temp"].to_list()) # could also use data.temp
# get average temp
print(mean(data["temp"].to_list()))
# mean using panda in-built function
print(data["temp"].mean())
# max value of column of temps
print(data["temp"].max())
# get row that has the max temp
print(data[data["temp"] == data["temp"].max()])
# get the condition of monday
monday = data[data["day"] == "monday"]
print(monday["condition"])
# create a dataframe from a dictionary
data_dict = {
"students": ["foo", "bar", "foobar"],
"scores": [12, 13, 14]
}
data_2 = pandas.DataFrame(data_dict)
print(data_2)
# then create a csv file from the data
data_2.to_csv("new_data_test.csv")
# Read a sample trading .csv file
# data = pandas.read_csv("trade_data.csv")
# net = round(data["Net Proceeds"].sum(),2)
# gross = round(data["Gross Proceeds"].sum(),2)
# commissions = round(data["Comm"].sum(),2)
# net_trading = round(net - gross, 2)
# sec = round(data["SEC"].sum(), 2)
# taf = round(data["TAF"].sum(),2)
# nscc = round(data["NSCC"].sum(),2)
# nasdaq = round(data["Nasdaq"].sum(),2)
# ecn_total = sec + taf + nscc + nasdaq
# qty = round(data["Qty"].sum())
# qty_average = round((data["Qty"].mean()))
# highest_price = round(data["Price"].max(), 2)
# currency_conversion = 0.82
#
# print(f"Total $ (Trading + Commissions): ${net}")
# print(f"Total (Trading): ${net_trading}")
# print(f"Total Platform Commissions: ${commissions}")
# print(f"Total ECN Commissions: ${ecn_total}")
# print(f"Total Shares Traded: {qty}")
# print(f"Average Shares Traded: {qty_average}")
# print(f"Highest Priced Share: ${highest_price}")
# print("*****************************************")
# print(f"Total € (Trading + Commissions): €{round(int(net) * currency_conversion, 2)}")
# more advanced queries. Getting rows.
# setting max_val to the row that has the highest gross proceeds. Then
# getting the symbol of that row
# max_val = data[data["Gross Proceeds"] == data["Gross Proceeds"].max()]
# print(max_val["Symbol"])
# date = data[data["T/D"] == "02/22/2019"]
# rows_date = date[date["Symbol"] == "HYRE"]
# print(rows_date)
# 3. Using import pandas. Analysing squirrel data
data = pandas.read_csv("2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv")
all_primary = data["Primary Fur Color"]
gray = 0
cinnamon = 0
black = 0
for color in all_primary:
if color == "Gray":
gray += 1
elif color == "Cinnamon":
cinnamon += 1
elif color == "Black":
black += 1
# print(all_primary)
print(gray)
print(cinnamon)
print(black)
new_dict = {
"Fur Color": ["grey", "red", "black"],
"Count": [gray, cinnamon, black]
}
# convert the dataframe to a dictionary
data_for_csv = pandas.DataFrame(new_dict)
# create a new csv file with the data
data_for_csv.to_csv("squirrel_count.csv")
# alternate method for squirrel count
data = pandas.read_csv("2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv")
gray_count = len(data[data["Primary Fur Color"] == "Gray"])
red_count = len(data[data["Primary Fur Color"] == "Cinnamon"])
black_count = len(data[data["Primary Fur Color"] == "Black"])
new_dict = {
"Fur Color": ["grey", "red", "black"],
"Count": [gray_count, red_count, black_count]
}
data_for_csv = pandas.DataFrame(new_dict)
data_for_csv.to_csv("squirrel_count.csv") |
bc281f1622eb0b0664ffb140f58c11e8a01bae0d | SSungCh/Algorithm | /SW academy/level1/15.py | 115 | 3.640625 | 4 | num1, num2 = map(int, input().split())
print('''{}
{}
{}
{}'''.format(num1+num2, num1-num2, num1*num2, num1//num2)) |
2ef0aa20f9042b030a16c36e6f3266b1ea88dc69 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_116/743.py | 1,691 | 3.546875 | 4 | T = int(raw_input())
def search_horizontal(table, sym):
cnt = 0
for i in xrange(0,4):
for j in xrange(0,4):
if (table[i][j] == sym or table[i][j] == 'T'): cnt+=1
else: break
if (cnt == 4): return True
else: cnt = 0
return False
def search_vertical(table, sym):
cnt = 0
for i in xrange(0,4):
for j in xrange(0,4):
if (table[j][i] == sym or table[j][i] == 'T'): cnt+=1
else: break
if (cnt == 4): return True
else: cnt = 0
return False
def search_diagonal(table, sym):
cntl = 0
cntr = 0
for i in xrange(0,4):
if (table[i][i] == sym or table[i][i] == 'T'): cntl+=1
if (cntl == 4): return True
j = 0
for i in xrange(3,-1,-1):
if (table[j][i] == sym or table[j][i] == 'T'): cntr+=1
j+=1
return (cntr == 4)
def still_playing(table):
for i in xrange(0,4):
if (table[i].count('.') > 0):
return True
return False
if __name__ == "__main__":
for c in xrange(1,T+1):
table = []
for i in xrange(0,4):
table.append(raw_input())
if (c < T): raw_input()
msg = ''
if (search_horizontal(table, 'O') or \
search_vertical(table, 'O') or \
search_diagonal(table, 'O')):
msg = 'O won'
elif (search_horizontal(table, 'X') or \
search_vertical(table, 'X') or \
search_diagonal(table, 'X')):
msg = 'X won'
elif (still_playing(table)):
msg = 'Game has not completed'
else:
msg = 'Draw'
print 'Case #%d: %s' % (c, msg)
|
26c4b3e373226a68b234c49e3b578a0af8c39d4f | yiqin/HH-Coding-Interview-Prep | /Use Python/SpiralMatrix.py | 1,348 | 3.609375 | 4 | class Solution(object):
"""docstring for Solution"""
def spiralOrder(self, matrix):
# print(matrix[0][1])
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
m = len(matrix)
n = len(matrix[0])
marked = [[True for i in range(n)] for j in range(m)]
# print(marked)
result = []
x = 0
y = 0
def addResult():
result.append(matrix[x][y])
marked[x][y] = False
addResult()
direction = 0
# modular
# 0 right
# 1 down
# 2 right
# 3 up
while True:
# print(x, y)
if direction%4 == 0:
if y+1 < m and marked[x][y+1]:
y = y+1
addResult()
continue
else:
direction += 1
print(direction)
elif direction%4 == 1:
if x+1 < n and marked[x+1][y]:
x = x + 1
addResult()
continue
else:
direction += 1
elif direction%4 == 2:
if y-1 >= 0 and marked[x][y-1]:
y = y - 1
addResult()
continue
else:
direction += 1
else:
if x-1 >= 0 and marked[x-1][y]:
x = x - 1
addResult()
continue
else:
direction += 1
# print("This is a break")
# break
if len(result) == (m-1)*(n-1):
break
print(result)
return result
# [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
solution = Solution()
solution.spiralOrder(matrix) |
cd89488a862d33d91663b74505f4c121cd8defc4 | liuxuesong0525/week3 | /Quest/Q3.py | 383 | 3.984375 | 4 | #编写程序,生成一个包含20个随机整数的列表,
# 然后对其中偶数下标(下标即列表元素的索引)的元素进行降序排列,
# 奇数下标的元素不变。(提示:使用切片。)
import random
list=[]
for i in range(20):
list.append(random.randint(1,100))
print(list)
list[::2]=sorted(list[::2],reverse=True)
print("降序排序",list) |
452fb9ffa405d0a749d056a2e0b55baf4242aa30 | Darshnadas/100_python_ques | /DAY11/day11.43.py | 209 | 3.953125 | 4 | """
Write a program which can filter() to make a list whose elements are even number between 1 and 20
(both included).
"""
def even(i):
return (i%2 == 0)
num = filter(even, range(1,21))
print(list(num)) |
ba0d82fae83685e82090ae27da47f579d668804d | DenisKalinin/python_cns | /homework/lesson 3/2-3.py | 1,105 | 4.28125 | 4 | #3. Написать функцию arithmetic, принимающую 3 аргумента: первые 2 - числа, третий - операция,
# которая должна быть произведена над ними. Если третий аргумент +, сложить их; если —, то вычесть;
# * — умножить; / — разделить (первое на второе). В остальных случаях вернуть строку "Неизвестная операция".
print("Введите первое число:")
a = int(input())
print("Введите второе число:")
b = int(input())
print("Введите знак +, -, * или /:")
c = input()
def arithmetic(a, b, c):
if c == '+':
return (a + b)
elif c == '-':
return(a - b)
elif c == '*':
return(a * b)
elif c == '/':
if b != 0:
return(a / b)
else:
return("Нельзя делить на ноль.")
else:
return("Неизвестная операция")
print(arithmetic(a, b, c)) |
744737a4569f510f06825a8e9e0127a2fcd973f6 | avish1990/Python | /listcount.py | 118 | 3.703125 | 4 | #!/usr/bin/python
mylist = ['spam', 'ham', 'eggs']
#print mylist
#new = ', '.join(mylist)
for i in mylist:
print i
|
182eac5d5a691cbe145b161a933e1fe978a8a947 | pyminsk/py | /ii.py | 854 | 3.734375 | 4 | import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ("Эй на палубе! Я Ужасный пират Робертс, и у меня есть секрет!")
print ("Это число от 1 до 99. Я дам тебе 6 попыток.")
print ("Твой вариант?")
print (secret)
guess = input
while guess != secret and tries < 7:
if guess < secret :
print ("Это слишком мало, презренный пес!")
elif guess > secret:
print ("Это слишком много, сухопутная крыса!")
tries = tries + 1
if guess == secret:
print ("Хватит! Ты угадал мой секрет!")
else:
print ("Попытки кончились!")
print ("Это число ", secret)
print ("Попыток было", tries)
|
67b1f32eab1b09cf22e8ec4997b6e4e3f70fd23a | patruong/Macroeconomy-TermPaper | /TermPaper/codes_and_csv/Python_OBS_kanStrula/CsvOrderReverser.py | 813 | 3.546875 | 4 | """
THIS PROGRAM CALCULATES CORRELATION FOR FORMATED AND SORTED TIME SERIES
CREATED FOR ME2720 Macroeconomics for business VT2016
NOTES:
Assuming format of data is:
Country - Time series (n-times) - avg
"""
import csv
#Read in files
rawdata = []
with open('US_CPI_raw_r.csv') as csvfile:
reader = csv.reader(csvfile, delimiter = ";")
for row in reader:
rawdata.append(row)
#Reverse Data
ReverseData=[]
#REVERSE ORDER FOR US
for i in reversed(rawdata):
ReverseData.append(i)
# DEFINE CSV-WRITER FUNCTION
def csvWrite(data, file):
with open(file, 'a', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter = ";")
writer.writerow(data)
return
for i in ReverseData:
csvWrite(i,"US_CPI_raw.csv")
|
08722f05406780cfd19a7d07e26285f0f32aa06e | WoodsChoi/algorithm | /al/al-147.py | 1,904 | 4.3125 | 4 | # 对链表进行插入排序
# medium
'''
对链表进行插入排序。
从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。
插入排序算法:
插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insertion-sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
------------------------------------
题解:模拟插入排序即可
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
hair = ListNode(-1)
hair.next = head
pre, tail = hair, hair.next
while tail != None:
p = hair
insert = False
while p.next != tail:
if (p == hair or tail.val > p.val) and tail.val <= p.next.val:
tmp = tail.next
pre.next = tmp
tail.next = p.next
p.next = tail
tail = tmp
insert = True
break
else:
p = p.next
if not insert:
pre = tail
tail = tail.next
return hair.next
|
9264a644f83df28d0cb439c18a645e66e1ba7a45 | ashwani1310/Multiple-Linear-Regression | /multiple_linear_regression_self.py | 2,595 | 4.03125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri May 5 05:36:04 2017
@author: ashwani
"""
#The code is based upon the foolowing assumption that the last column of features contain
#a categorical data with three categories.
#To Import the needed libraries which will help us build our model
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#
#Here, the data set is being imported and the features and labels
#are stored in separate arrays
data = pd.read_csv('any csv file to be added here containing multiple input feature')
Features = data.iloc[:, :-1].values # here the label is the last column and the rest are features.
Label = data.iloc[:, 4].values
#Now, to encode the categorical data into dummy variables
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
feature_encoder = LabelEncoder()
Features[:,3] = feature_encoder.fit_transform(Features[:,3])
feature_one_encoder = OneHotEncoder(categorical_features = [3])
Features = feature_one_encoder.fit_transform(Features).toarray()
#Always remove one dummy variable from total
Features = Features[:, 1:]
#This is to split training and testing data from the imported dataset
from sklearn.cross_validation import train_test_split
Features_train, Features_test, Label_train, Label_test = train_test_split(Features, Label, test_size = 0.2, random_state = 0)
#Now making the model
from sklearn.linear_model import LinearRegression
reg_model = LinearRegression()
reg_model.fit(Features_train,Label_train)
#Now to test the model results
Label_pred = reg_model.predict(Features_test)
#Optimizing our model using backward elimination
import statsmodels.formula.api as stat
Features = np.append(arr = np.ones((50,1)).astype(int), values = Features, axis = 1)
Features_optimal = Features[:, [0,1,2,3,4,5]]
reg_model_least_squares = stat.OLS(endog = Label, exog = Features_optimal).fit()
reg_model_least_squares.summary()
Features_optimal = Features[:, [0, 1, 3, 4, 5]]
reg_model_least_squares = stat.OLS(endog = Label, exog = Features_optimal).fit()
reg_model_least_squares.summary()
Features_optimal = Features[:, [0, 3, 4, 5]]
reg_model_least_squares = stat.OLS(endog = Label, exog = Features_optimal).fit()
reg_model_least_squares.summary()
Features_optimal = Features[:, [0, 3, 5]]
reg_model_least_squares = stat.OLS(endog = Label, exog = Features_optimal).fit()
reg_model_least_squares.summary()
Features_optimal = Features[:, [0, 3]]
reg_model_least_squares = stat.OLS(endog = Label, exog = Features_optimal).fit()
reg_model_least_squares.summary() |
59d076f576ade521879c571db4174ba35e4a9676 | ZiyaoGeng/LeetCode | /Code/70.py | 451 | 3.671875 | 4 |
class Solution:
"""
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
count = self.climbStairs(n - 1) + self.climbStairs(n - 2)
return count
"""
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
stairs = [1, 2]
for i in range(2, n):
stairs.append(stairs[i-1] + stairs[i-2])
return stairs[n-1]
s = Solution()
print(s.climbStairs(6)) |
52f8c022a404fd745ad13cf7987c0611ebc0b432 | daniel10012/python-onsite | /week_04/web_scraping/01_your_page.py | 827 | 3.546875 | 4 | '''
Using python's request library, retrieve the HTML of the website you created
that now lives online at <your-gh-username>.github.io/<your-repo-name>
BONUS: extend your python program so that it reads your original HTML file
and returns True if the HTML from the response is the same as the
the contents of the original HTML file.
'''
import requests
url = "https://daniel10012.github.io/staticpage/"
r = requests.get(url).text
with open("copymysite.html", "w") as fout:
fout.write(r)
with open("copymysite.html", "r") as fin:
content_copy = fin.read()
if r == content_copy:
print("the 2 files are identical")
with open("original.html", "r") as fin:
content_original = fin.read()
if r == content_original:
print("site = original")
else:
print("oops")
|
ca26b35028dd28008f1b66dd6e36113f2ee4bc12 | tuhiniris/Python-ShortCodes-Applications | /patterns2/spiral number pattern.py | 468 | 3.546875 | 4 | '''
Pattern:
Spiral number pattern:
Enter number of rows: 5
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
'''
n=int(input('Enter number of rows: '))
for row in range(0,2*n-1):
for column in range(0,(2*n-1)):
min= row if row < column else column
min= min if min < ((n*2)-1)-row-1 else (((n*2)-1)-row)-1
min= min if min < (((n*2)-1)-column) else (((n*2)-1)-column)-1
print(n-min,end=' ')
print() |
ffca78a3770e024be87a248b02e0269990e11d55 | Aiooon/MyLeetcode | /python/017. 电话号码的字母组合.py | 1,468 | 3.75 | 4 | """
17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
date: 2021年3月26日
"""
from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
idx2chr = [ [], [], ['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r', 's'],
['t', 'u', 'v'],
['w', 'x', 'y', 'z']]
res = []
def backtrack(sol, res, digits_idx):
if len(sol) == len(digits):
res.append(sol)
return
chars = idx2chr[int(digits[digits_idx])]
for c in chars:
sol += c
backtrack(sol, res, digits_idx + 1)
sol = sol[:-1]
backtrack("", res, 0)
return res
digits = "23"
print(Solution().letterCombinations(digits)) |
076ddd08c44f90cb4f054a1c416a44ba96ab8e3e | codeforcauseorg-archive/DSA-Live-Python-Jun-0621 | /lecture-14/dicefaces.py | 535 | 3.65625 | 4 | def dice(target, faces):
if target == 0:
return 1
count = 0
for face in range(1, faces+1):
if face > target:
break
count += dice(target-face, faces)
return count
def dicepaths(target, faces, solution=[]):
if target == 0:
print(solution)
return
for face in range(1, faces+1):
if face > target:
break
solution.append(face)
dicepaths(target-face, faces, solution)
solution.pop()
return
dicepaths(4, 3)
|
c081f9329be6f0be883b9278e4e4c0ec3475d0e9 | PangYunsheng8/LeetCode | /剑指offer/对称的二叉树.py | 361 | 3.5625 | 4 | class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root: return True
def recu(t1, t2):
if not t1 and not t2: return True
if not t1 or not t2 or t1.val != t2.val: return False
return recu(t1.left, t2.right) and recu(t1.right, t2.left)
return recu(root.left, root.right) |
de48460c3d7d59d18d47dd272164308122510f15 | 999Hans/SWE-Academy | /8. 함수/2. 가위바위보.py | 496 | 3.734375 | 4 | a1 = input()
a2 = input()
x = input()
y = input()
def win(x1, x2):
if (x1 == "가위" and x2 == "바위") or (x2 == "가위" and x1 == "바위"):
print("바위가 이겼습니다!")
elif (x1 == "가위" and x2 == "보") or (x2 == "가위" and x1 == "보"):
print("가위가 이겼습니다!")
elif (x1 == "보" and x2 == "바위") or (x2 == "보" and x1 == "바위"):
print("보가 이겼습니다!")
else:
print("비겼습니다!")
win(x,y)
|
d5a4ac7be046ee570f6cd657623d9d41c6e6b61f | Aleks8830/PythonPY100 | /Занятие1/Практические_задания/task2_1/main.py | 229 | 3.6875 | 4 | input_str = input('Введите строку Hello World: ')
print(input_str,type(input_str))
# TODO c помощью функции print рачпечатайте значение переменной input_str и её тип
|
230fe4d0d7175d67be8cd5f1a62dbbd7c51d2db3 | MaphsterB/advent2017 | /solvers/day18.py | 7,794 | 3.78125 | 4 | """
--- Day 18: Duet ---
You discover a tablet containing some strange assembly code labeled simply
"Duet". Rather than bother the sound card with it, you decide to run the code
yourself. Unfortunately, you don't see any documentation, so you're left to
figure out what the instructions mean on your own.
It seems like the assembly is meant to operate on a set of registers that are
each named with a single letter and that can each hold a single integer. You
suppose each register should start with a value of 0.
There aren't that many instructions, so it shouldn't be hard to figure out what
they do. Here's what you determine:
- snd X plays a sound with a frequency equal to the value of X.
- set X Y sets register X to the value of Y.
- add X Y increases register X by the value of Y.
- mul X Y sets register X to the result of multiplying the value contained
in register X by the value of Y.
- mod X Y sets register X to the remainder of dividing the value contained
in register X by the value of Y (that is, it sets X to the result of X
modulo Y).
- rcv X recovers the frequency of the last sound played, but only when the
value of X is not zero. (If it is zero, the command does nothing.)
- jgz X Y jumps with an offset of the value of Y, but only if the value of X
is greater than zero. (An offset of 2 skips the next instruction, an
offset of -1 jumps to the previous instruction, and so on.)
Many of the instructions can take either a register (a single letter) or a
number. The value of a register is the integer it contains; the value of a
number is that number.
After each jump instruction, the program continues with the instruction to which
the jump jumped. After any other instruction, the program continues with the
next instruction. Continuing (or jumping) off either end of the program
terminates it.
For example:
set a 1
add a 2
mul a a
mod a 5
snd a
set a 0
rcv a
jgz a -1
set a 1
jgz a -2
- The first four instructions set a to 1, add 2 to it, square it, and then
set it to itself modulo 5, resulting in a value of 4.
- Then, a sound with frequency 4 (the value of a) is played.
- After that, a is set to 0, causing the subsequent rcv and jgz instructions
to both be skipped (rcv because a is 0, and jgz because a is not greater
than 0).
- Finally, a is set to 1, causing the next jgz instruction to activate,
jumping back two instructions to another jump, which jumps again to the
rcv, which ultimately triggers the recover operation.
At the time the recover operation is executed, the frequency of the last sound
played is 4.
What is the value of the recovered frequency (the value of the most recently
played sound) the first time a rcv instruction is executed with a non-zero
value?
"""
import multiprocessing as mp
import queue
import re
class BadDuetVM():
"""Simulator VM for Part 1"""
INSTR_RX = re.compile(r"(snd|set|add|mul|mod|rcv|jgz)\s+(\S+)(?:\s+(\S+))?")
def __init__(self):
self.regs = {}
self.played = []
self.recovers = []
self.ip = 0
@classmethod
def parse(cls, lines):
program = []
for line in lines:
m = re.match(cls.INSTR_RX, line)
if not m: raise AssertionError()
g = [x for x in m.groups() if x is not None]
method = getattr(cls, g[0])
args = g[1:]
program.append((method, args))
return program
def fet(self, x):
try:
return int(x)
except ValueError:
return self.regs.get(x, 0)
def execute(self, program, debug=False):
while 0 <= self.ip < len(program):
(method, args) = program[self.ip]
ret = method.__call__(self, *args)
if debug:
print(method.__name__, args)
if ret is not None:
return self.recovers[0]
self.ip += 1
def snd(self, x):
self.played.append(self.fet(x))
def set(self, x, y):
self.regs[x] = self.fet(y)
def add(self, x, y):
self.regs[x] = self.regs.get(x, 0) + self.fet(y)
def mul(self, x, y):
self.regs[x] = self.regs.get(x, 0) * self.fet(y)
def mod(self, x, y):
self.regs[x] = self.regs.get(x, 0) % self.fet(y)
def rcv(self, x):
if self.fet(x):
self.recovers.append(self.played[-1])
return True
def jgz(self, x, y):
if self.fet(x) > 0:
self.ip += self.fet(y) - 1
class DuetVM(BadDuetVM):
"""Overrides the 'incorrect' parts."""
ASK_TO_WAIT = 1
DONE_WAITING = 2
TERMINATING = 3
def __init__(self, id_):
self.regs = {}
self.ip = 0
self.sent = []
self.received = []
self.queue = mp.Queue()
self.proc = None
self.partner = None
self.lock = None
def start(self, program, pipe_conn, debug=False):
self.proc = mp.Process(
target=self.execute,
args=[program, pipe_conn],
kwargs=dict(debug=debug),
)
self.proc.start()
def join(self):
return self.proc.join()
def execute(self, program, pipe_conn, debug=False):
while 0 <= self.ip < len(program):
(method, args) = program[self.ip]
if debug:
print(method.__name__, args)
# If both rcv at the same time, we deadlock.
# Ask permission before waiting.
if method.__name__ == "rcv":
if not self.lock.acquire(block=True, timeout=0.1):
print(self, "QUIT")
break
ret = method.__call__(self, *args)
if ret:
break
self.lock.release()
else:
method.__call__(self, *args)
self.ip += 1
pipe_conn.send(self.ip)
pipe_conn.send(self.sent)
pipe_conn.send(self.received)
def pair(self, partner):
self.lock = mp.Semaphore()
partner.lock = self.lock
self.partner = partner
partner.partner = self
def snd(self, x):
val = self.fet(x)
self.partner.queue.put(val)
self.sent.append(val)
def rcv(self, x):
try:
val = self.queue.get(timeout=2)
except queue.Empty:
return True
self.regs[x] = val
self.received.append(val)
class DuetCoordinator:
"""Manages two duet subprocesses to detect deadlock."""
def __init__(self):
self.vm0 = DuetVM(0)
self.vm1 = DuetVM(1)
self.vm0.pair(self.vm1)
self.vm0_waiting = False
self.vm1_waiting = False
def run(self, program, debug=False):
# Talk to both subprocesses
(recv0, send0) = mp.Pipe(duplex=False)
(recv1, send1) = mp.Pipe(duplex=False)
self.vm0.start(program, send0, debug=debug)
self.vm1.start(program, send1, debug=debug)
self.vm0.ip = recv0.recv()
self.vm0.sent = recv0.recv()
self.vm0.received = recv0.recv()
self.vm1.ip = recv1.recv()
self.vm1.sent = recv1.recv()
self.vm1.received = recv1.recv()
self.vm0.join()
self.vm1.join()
def part1(input_lines):
"""
Run a bad duet VM until it executes a rcv instruction.
"""
vm = BadDuetVM()
program = BadDuetVM.parse(input_lines)
return vm.execute(program)
def part2(input_lines):
"""
Run two correct duet VM's until both terminate (or deadlock).
"""
c = DuetCoordinator()
program = DuetVM.parse(input_lines)
c.run(program)
return len(c.vm1.sent)
|
47cebd3b8c92728dda3218dec4936e96e1f5f831 | arattha/CodingTest | /백수/코테공부/greedy/Check If a String Can Break Another String.py | 1,314 | 3.625 | 4 | ################################################################################
#1433. Check If a String Can Break Another String #
#https://leetcode.com/problems/check-if-a-string-can-break-another-string/ #
################################################################################
#s1의 순열중 하나가 s2의 순열중 하나보다 모든 인덱스에서 알파벳값이 더 크거나 같아야 한다.
#또는 반대의 경우
class Solution:
#모든 인덱스에서 알파벳 값이 더 큰지 판단한다.
def canBreak(self, s1: str, s2: str) -> bool:
for i in range(len(s1)):
#하나라도 작으면 실패
if s1[i] < s2[i]:
return False
return True
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
#순서를 비교하기 위해서 정렬
s1 = sorted(s1)
s2 = sorted(s2)
ans = False
#두가지 경우 모두 판단한다
#s1의 모든 알파벳이 더 크거나 같은 경우
if s1[0] >= s2[0]:
ans = ans or self.canBreak(s1,s2)
#s2의 모든 알파벳이 더 크거나 같은 경우
if s2[0] >= s1[0]:
ans = ans or self.canBreak(s2,s1)
return ans |
e7d267b711545d447783c4b9982d1e89f9d2432c | dementrock/acm | /berkeley_programming_contest_2012/inst.eecs.berkeley.edu/~ctest/contest/test-data/1/subm/make-data | 490 | 3.6875 | 4 | #!/usr/bin/env python
# -*-Python-*-
import re, sys, random
random.seed(sys.argv[1])
D = int(sys.argv[2])
args = map(int, sys.argv[3:])
for NC, NR in zip(args[::2], args[1::2]):
print NR
roads = set([])
for i in xrange(NR):
c1 = c2 = random.randint(1, NC)
while c1 == c2 or (c1, c2) in roads:
c2 = random.randint(1, NC)
roads.add((c1,c2))
roads.add((c2,c1))
print "C" + str(c1), "C" + str(c2), random.randint(1, D)
print 0
|
36efd8c42bfbfd902d0c62aa6ea0d5a8dd0a6eb6 | djm158/pygame-bouncing-ball | /ball.py | 659 | 3.84375 | 4 | import pygame
class Ball(pygame.sprite.Sprite):
"""
Ball class
attribute: velocity
methods: update
"""
def __init__(self, color, position, radius):
# call super class constructor
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((radius*2, radius*2))
self.image.fill((0, 0, 0))
pygame.draw.circle(self.image, color, (radius, radius), radius)
self.rect = self.image.get_rect()
self.rect.center = position
self.velocity = 3
def update(self):
self.velocity = self.velocity + .25
self.rect.y += self.velocity
|
adec411221896366552f1799b15e45e992080360 | zikfood/budg-intensive | /day_1/flow_control/task_2/implementation.py | 218 | 3.6875 | 4 | def convert_temperature(value, to_scale):
if to_scale == "F":
result = value * 9 / 5 + 32
elif to_scale == "C":
result = (value - 32) * 5 / 9
else:
result = value
return result
|
0cfac75b224420b1bea986625d1b43bcfeeeb1cf | ArkadiyShkolniy/python_lesson_2 | /for.py | 366 | 4.125 | 4 | # Циклы For
# Простейший цикл For
for i in range(10): # range (start, stop, step)
print(i)
if i == 5: break
for i in range(5):
answer = input ("Какая марка авто?")
if answer == "Volvo":
print("Вы правы")
break
for i in range(10):
if i == 9: break
if i < 3: continue
else: print(i) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.