blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
5d105331052818558742bc74a88b8bc02978a40a | wenjie711/Leetcode | /python/137_single_Num2.py | 452 | 3.78125 | 4 | #!/usr/bin/env python
#coding: utf-8
class Solution:
# @param {integer[]} nums
# @return {integer}
def singleNumber(self, nums):
one = 0
two = 0
three = 0
for i in range(len(nums)):
two |= one & nums[i]
one ^= nums[i]
three = two & one
one ^= three
two ^= three
return one
s = Solution()
print(s.singleNumber([-2,-2,1,1,-3,1,-3,-3,-4,-2]))
|
39068a965cfff9d2ca75fdfe8135d25c52b13142 | jovicamitrovic/ori-2016-siit | /vezbe/01-linreg/src/solutions/linreg_simple.py | 1,645 | 3.578125 | 4 | """
@author: SW 15/2013 Dragutin Marjanovic
@email: dmarjanovic94@gmail.com
"""
from __future__ import print_function
import random
import matplotlib.pyplot as plt
def linear_regression(x, y):
# Provjeravamo da li su nam iste dimenzije x i y
assert(len(x) == len(y))
# Duzina liste x i y
n = len(x)
# Racunamo srednju vrijednost x i y
x_mean = float(sum(x))/n
y_mean = float(sum(y))/n
# X predstavlja (xi - x_mean) za svako X koje pripada listi 'x'
X = [xi - x_mean for xi in x]
Y = [yi - y_mean for yi in y]
# Brojilac nagiba funkcije (b iz formule)
numerator = sum([i*j for i, j in zip(X, Y)])
# Imenilac nagiba funkcije (b iz formule)
denominator = sum([i**2 for i in X])
# TODO 1: implementirati linearnu regresiju
# Koristimo formulu za b iz fajla 'ori-2016-siit-01-linreg.ipynb'
slope = numerator/denominator
intercept = y_mean - slope*x_mean
return slope, intercept
def predict(x, slope, intercept):
# TODO 2: implementirati racunanje y na osnovu x i parametara linije
return intercept + slope*x
def create_line(x, slope, intercept):
y = [predict(xx, slope, intercept) for xx in x]
return y
if __name__ == '__main__':
x = range(50) # celobrojni interval [0,50]
random.seed(1337) # da rezultati mogu da se reprodukuju
y = [(i + random.randint(-5, 5)) for i in x] # y = x (+- nasumicni sum)
slope, intercept = linear_regression(x, y)
line_y = create_line(x, slope, intercept)
plt.plot(x, y, '.')
plt.plot(x, line_y, 'b')
plt.title('Slope: {0}, intercept: {1}'.format(slope, intercept))
plt.show()
|
fd10e971ea57316b742f15932f0c0d17613e6e4f | jovicamitrovic/ori-2016-siit | /vezbe/01-linreg/src/bonus/birth_rate.py | 1,521 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
@author: Stefan Ristanović SW3/2013
@email: st.keky@gmail.com
- Description:
Birth Rates,
per capita income,
proportion (ratio?) of population in farming,
and infant mortality
during early 1950s for 30 nations.
- Conclusion:
In that period of time, the biggest impact on birth rate had the
proportion of population in farming which is excpected result knowing
history of that time. Slightly less influence had infant mortality, and
per capita income had almost none of the impact (which is, one could say,
a surprising result knowing nowadays situation).
"""
from __future__ import print_function
import csv
from sklearn import linear_model
import numpy
def read_csv(file_name):
with open(file_name) as csvfile:
birth_rate, per_cap_inc, prop_on_farms, infant_mort = [], [], [], []
csvreader = csv.reader(csvfile, delimiter=',')
for row in csvreader:
birth_rate.append(float(row[1]))
per_cap_inc.append(float(row[2]))
prop_on_farms.append(float(row[3]))
infant_mort.append(float(row[4]))
# create and transpose numpy array
x = numpy.array([per_cap_inc, prop_on_farms, infant_mort]).transpose()
return x, birth_rate
if __name__ == '__main__':
# read data from dataset
x, y = read_csv('birth_rate.csv');
lm = linear_model.LinearRegression()
lm.fit (x, y)
print(lm.coef_)
print(lm.intercept_) |
afe9f6bb6ba3598cb26b52432df699531c19d968 | ChihChiu29/ml_lab | /image_recognition/hotspot_on_noise_classification.py | 4,037 | 4.0625 | 4 | """Academical examples on image classifications.
This module is an experiment for classifying images. The goal is to train a
model that can successfully identify images annotated in certain way. The
annotation is a small image that's super-imposed on a background image.
"""
import keras
import numpy
from keras import layers
from keras import models
from keras import optimizers
from matplotlib import pyplot as plt
from sklearn import metrics
from qpylib import logging
from qpylib import t
IMAGE_SIZE = 128
# Image array is a 3d float array; its 1st dimension is y and 2nd dimension
# is x, and 3rd dimension has size 1 and it is the grey scale. This convention
# is chosen to match pyplot.imshow.
Image = numpy.array
def CreateBlankImage(
height: int,
width: int,
) -> Image:
"""Creates a blank (0) image."""
return numpy.zeros((width, height, 1), dtype=float)
def CreateBlankImageWithNoise(
height: int,
width: int,
noise_strength: float = 0.1,
) -> Image:
"""Creates a almost blank (0) image."""
return numpy.random.uniform(0.0, noise_strength, (width, height, 1))
def AddBoxToImage(img: Image, y: int, x: int, size: int = 5):
"""Adds a box (color 1) to the image."""
img[y:y + size, x:x + size] = 1.0
def CreateImageData(
num_blank_images: int,
num_annotated_images: int,
height: int = IMAGE_SIZE,
width: int = IMAGE_SIZE,
) -> t.Tuple[numpy.array, numpy.array]:
"""Creates an image data set of given size.
Args:
num_blank_images: number of blank images to generate.
num_annotated_images: number of annotated images.
height: image height.
width: image width.
Returns:
A tuple of images and labels (one-hot representation), order is randomized.
"""
images_and_labels = []
for _ in range(num_blank_images):
images_and_labels.append(
(CreateBlankImageWithNoise(height, width), numpy.array([1.0, 0.0])))
for _ in range(num_annotated_images):
img = CreateBlankImageWithNoise(height, width)
AddBoxToImage(
img,
y=numpy.random.randint(0, height - 1),
x=numpy.random.randint(0, width - 1))
images_and_labels.append((img, numpy.array([0.0, 1.0])))
numpy.random.shuffle(images_and_labels)
return (
numpy.array([e[0] for e in images_and_labels]),
numpy.array([e[1] for e in images_and_labels]))
def CreateDefaultOptimizer() -> optimizers.Optimizer:
"""Creates a default optimizer."""
# Ref:
# https://jaromiru.com/2016/10/03/lets-make-a-dqn-implementation/
return optimizers.RMSprop(lr=0.00025)
def CreateConvolutionModel(
image_shape: t.Tuple[int, int, int],
activation: t.Text = 'relu',
optimizer: optimizers.Optimizer = None,
) -> keras.Model:
if optimizer is None:
optimizer = CreateDefaultOptimizer()
model = models.Sequential()
model.add(layers.Conv2D(
16,
kernel_size=4,
activation=activation,
input_shape=image_shape,
))
model.add(layers.Conv2D(
16,
kernel_size=4,
activation=activation))
model.add(layers.Flatten())
model.add(layers.Dense(units=2))
model.compile(loss='mse', optimizer=optimizer)
return model
def PlotImage(img: Image):
y_size, x_size, _ = img.shape
plt.imshow(img.reshape(y_size, x_size))
plt.show()
def MainTest():
images, labels = CreateImageData(num_blank_images=5, num_annotated_images=5)
for idx in range(5):
logging.printf('Label %d: %s', idx, labels[idx])
PlotImage(images[idx])
def MainTrain():
images, labels = CreateImageData(
num_blank_images=5000,
num_annotated_images=5000,
)
model = CreateConvolutionModel((IMAGE_SIZE, IMAGE_SIZE, 1))
model.fit(images, labels)
images, labels = CreateImageData(
num_blank_images=50,
num_annotated_images=50,
)
labels_argmax = labels.argmax(axis=1)
predicted_labels = model.predict(images)
predicted_labels_argmax = predicted_labels.argmax(axis=1)
print(metrics.confusion_matrix(predicted_labels_argmax, labels_argmax))
if __name__ == '__main__':
# MainTest()
MainTrain()
|
12daf4f361701b49e3a14820d6bb91d337497de1 | bjskkumar/Python_coding | /test.py | 1,591 | 4.28125 | 4 | # name = "Jhon Smith"
# age = 20
# new_patient = True
#
# if new_patient:
# print("Patient name =", name)
# print("Patient Age = ", age)
#
# obtaining Input
name = input("Enter your name ")
birth_year = input (" Enter birth year")
birth_year= int(birth_year)
age = 2021 - birth_year
new_patient = True
if new_patient:
print("Patient name =", name)
print("Patient Age = ", age)
# String
# Name = "Saravana Kumar"
# print(Name.find("Kumar"))
# print(Name.casefold())
# print(Name.replace("Kumar", "Janaki"))
# print("Kumar" in Name)
# Arithmetic Operations
# X = (10 +5) * 5
# print(X)
# Comparison
# X = 3 > 2
#
# if X:
# print("Greater")
# Logical Operators
# age = 25
#
# print(age >10 and age <30)
#
# print(age>10 or age <30)
#
# print( not age > 30)
# If statements
# Temp = 30
#
# if Temp >20:
# print("its hot")
# elif Temp < 15:
# print("its cool")
#while loops
# i = 1
# while i <= 5:
# print(i * '*')
# i = i+1s
# Lists
# names = ["saravana", "Kumar", "Balakrishnan", "Janaki"]
# print(names[0])
# print(names[1:4])
# for name in names:
# print(name)
# List functions
#
# names = ["saravana", "Kumar", "Balakrishnan", "Janaki"]
# names.append("jhon")
# print(names)
# names.remove("jhon")
# print(names)
# print("Kumar" in names)
# print(len(names))
# for loops
# names = ["saravana", "Kumar", "Balakrishnan", "Janaki"]
#
# for name in names:
# print(name)
#
# for name in range(4):
# print(name)
#
# number = range(4,10)
# for i in number:
# print(i)
# Tuples , immutable
# numbers = (1,2,3)
# print(numbers[0])
|
6f582a234b2c9264a2bf877047ac7c9a66b22ae4 | dnackat/cs50x-intro-to-comp-sci | /sentimental/vigenere.py | 1,727 | 4.03125 | 4 | # vigenere.py
import sys
import string
# Define a main function to match C code
def main():
# Check if input is correct
if len(sys.argv) == 1 or len(sys.argv) > 2 or not str.isalpha(sys.argv[1]):
print("Usage ./vignere k")
sys.exit(1)
else:
# Convert key to lowercase
key = str.lower(sys.argv[1])
# Create a dictionary containing numerical shifts corresponding to alphabets
shifts = {list(string.ascii_lowercase)[i]: i for i in range(26)}
# Get plaintext from user
p = input("plaintext: ")
# Get ready to print cyphertext
print("ciphertext: ", end="")
# Loop over all letters and do shifts
c = []
# Variable to keep track of position in keyword
t = 0
for k in range(len(p)):
# Check if letter is an alphabet
if str.isalpha(p[k]):
# Check if uppercase or lowercase
if str.isupper(p[k]):
# Shift by ASCII value (A = 0 instead of 65)
s = ord(p[k]) - 65
# Apply the ciphering formula
c.append(chr(((s + shifts[key[t % len(key)]]) % 26) + 65))
# Update keyword position
t += 1
else:
# Shift by ASCII value (a = 0 instead of 97)
s = ord(p[k]) - 97
# Apply the ciphering formula
c.append(chr(((s + shifts[key[t % len(key)]]) % 26) + 97))
# Update keyword position
t += 1
else:
c.append(p[k])
# Print ciphertext
for ch in c:
print(ch, end="")
# Print newline
print()
# Return 0 if successful
return 0
if __name__ == "__main__":
main() |
487e1b65563ee4502403216662ee64a4f119d78b | DmytroLopushanskyy/lab11_part2 | /polynomial/polynomial.py | 5,656 | 4.34375 | 4 | """
Implementation of the Polynomial ADT using a sorted linked list.
"""
class Polynomial:
"""
Create a new polynomial object.
"""
def __init__(self, degree=None, coefficient=None):
"""
Polynomial initialisation.
:param degree: float
:param coefficient: float
"""
if degree is None:
self._poly_head = None
else:
self._poly_head = _PolyTermNode(degree, coefficient)
self._poly_tail = self._poly_head
def degree(self):
"""
Return the degree of the polynomial.
:return:
"""
if self._poly_head is None:
return -1
return self._poly_head.degree
def __getitem__(self, degree):
"""
Return the coefficient for the term of the given degree.
:param degree: float
:return: float
"""
assert self.degree() >= 0, "Operation not permitted on an empty polynomial."
cur_node = self._poly_head
while cur_node is not None and cur_node.degree >= degree:
if cur_node.degree == degree:
break
cur_node = cur_node.next
if cur_node is None or cur_node.degree != degree:
return 0.0
return cur_node.coefficient
def evaluate(self, scalar):
"""
Evaluate the polynomial at the given scalar value.
:param scalar:
:return:
"""
assert self.degree() >= 0, "Only non -empty polynomials can be evaluated."
result = 0.0
cur_node = self._poly_head
while cur_node is not None:
result += cur_node.coefficient * (scalar ** cur_node.degree)
cur_node = cur_node.next
return result
def __add__(self, rhs_poly):
"""
Polynomial addition: newPoly = self + rhs_poly.
:param rhs_poly: Polynomial
:return: Polynomial
"""
return self.calculate("add", rhs_poly)
def __sub__(self, rhs_poly):
"""
Polynomial subtraction: newPoly = self - rhs_poly.
:param rhs_poly:
:return:
"""
return self.calculate("sub", rhs_poly)
def calculate(self, action, rhs_poly):
"""
Calculate math expression on Polynomial.
:param action: str
:param rhs_poly: Polynomial
:return: Polynomial
"""
degrees_set = set(self.get_all_degrees() + rhs_poly.get_all_degrees())
degrees_set = sorted(degrees_set, reverse=True)
final_pol = Polynomial()
for degree in degrees_set:
if action == "add":
coeff = self[degree] + rhs_poly[degree]
else:
coeff = self[degree] - rhs_poly[degree]
final_pol._append_term(degree, coeff)
return final_pol
def get_all_degrees(self):
"""
Get all degrees in the polynomial
:return: list
"""
degrees_list = []
next_node = self._poly_head
while next_node is not None:
degrees_list.append(next_node.degree)
next_node = next_node.next
return degrees_list
def __mul__(self, rhs_poly):
"""
Polynomial multiplication: newPoly = self * rhs_poly.
:param rhs_poly:
:return:
"""
self_next = self._poly_head
final_pol = Polynomial()
polynom_dict = dict()
while self_next is not None:
rhs_poly_next = rhs_poly._poly_head
while rhs_poly_next is not None:
degree = self_next.degree + rhs_poly_next.degree
coeff = self_next.coefficient * rhs_poly_next.coefficient
if degree in polynom_dict:
polynom_dict[degree] += coeff
else:
polynom_dict[degree] = coeff
rhs_poly_next = rhs_poly_next.next
self_next = self_next.next
degrees_set = sorted(polynom_dict.keys(), reverse=True)
for degree in degrees_set:
final_pol._append_term(degree, polynom_dict[degree])
return final_pol
def __str__(self):
"""
Polynomial string representation.
:return: str
"""
output = ""
if self._poly_head:
output = str(self._poly_head)
next_node = self._poly_head.next
while next_node is not None:
if str(next_node).startswith("- "):
output += " " + str(next_node)
else:
output += " + " + str(next_node)
next_node = next_node.next
return output
def _append_term(self, degree, coefficient):
"""
Add new link to polynomial.
:param degree: float
:param coefficient: float
:return: None
"""
new_node = _PolyTermNode(degree, coefficient)
if self._poly_tail is None:
self._poly_head = new_node
self._poly_tail = new_node
else:
self._poly_tail.next = new_node
self._poly_tail = new_node
class _PolyTermNode:
"""
Class for creating polynomial term nodes used with the linked list.
"""
def __init__(self, degree, coefficient):
self.degree = degree
self.coefficient = coefficient
self.next = None
def __str__(self):
"""
Prints the value stored in self.
__str__: Node -> Str
"""
if self.coefficient < 0:
return "- " + str(abs(self.coefficient)) + "x" + str(self.degree)
return str(self.coefficient) + "x" + str(self.degree)
|
ee30fcac54df14dc48870f687033ce02266bb5c9 | prasadnaidu1/django | /Adv python practice/QUESTIONS/14.py | 125 | 3.859375 | 4 | n=int(input("enter no :"))
lst=[]
for x in range(0,n):
if x%2!=0:
lst.append(x)
else:
pass
print(lst) |
cb25bb6cd9b6a5ef56ac747b131369787d0efa78 | prasadnaidu1/django | /Adv python practice/method override/KV RAO OVERRIDE2.py | 1,096 | 3.984375 | 4 | class numbers(object):
def __init__(self):
print("i am base class constructor")
def integers(self):
self.a=int(input("enter a value : "))
self.b=int(input("enter b value : "))
self.a,self.b=self.b,self.a
print("For swaping integers of a, b : ",self.a,self.b)
print("For swaping integers of b, a : ",self.b,self.a)
class strings(numbers):
def __init__(self):
super().__init__()
print("i am derived class constructor")
def put (self):
while True:
super().integers()
self.s1=input("enter first string : ")
self.s2=input("enter second string : ")
self.s1,self.s2=self.s2,self.s1
print("For swaping strings of s1, s2 : ",self.s1,self.s2)
print("For swaping strings of s2, s1 : ",self.s2,self.s1)
ans = input("to continue press y:")
if ans == 'y':
continue
else:
break
#calling block
s=strings()
s.put()
|
abb0668e938b64b6cf404a3d11aa50b2e4d1d463 | prasadnaidu1/django | /Adv python practice/OOPS/constructer.py | 798 | 3.78125 | 4 | class sample:
comp_name = "Sathya technologies"
comp_adds = "Hyderabad"
def __init__(self):
while True:
try:
self.employee_id = int(input("Enter a No : "))
self.employee_name = input("Enter a Name : ")
print("Company Name : ",sample.comp_name)
print("Company Adds : ",sample.comp_adds)
print("Employee Id : ", self.employee_id)
print("Employee Name : ", self.employee_name)
except:
print("invalid input")
ans=input("To Continue Press y : ")
if ans=="y" or ans=="Y":
continue
else:
break
def display(self):
pass
#calling block
s1 = sample()
s1.display()
|
d463732ff9853cf2872192e16a3ff1dda5ba763c | prasadnaidu1/django | /Adv python practice/OOPS2.py | 360 | 3.859375 | 4 | #Write a program on class example without creating any object.
class demo:
comp_name="Prasad Technologies"
Comp_adds="hyd"
@staticmethod
def dispaly(x,y):
print("Company Name:",demo.comp_name)
print("Company Adds :",demo.Comp_adds)
i=x
j=y
print("The sum of above values is:",i+j)
#calling block
demo.dispaly(20,40)
|
e597d95e27d3968b8316fcb844a7ec26576dbca7 | prasadnaidu1/django | /Adv python practice/sisco3.py | 5,404 | 3.859375 | 4 | lst = []
while True:
name = input("Enter Name : ")
lst.append(name)
ans = input("Continue press y : ")
if ans == "y":
continue
else:
print(lst)
res = len(lst)
print(res)
break
class management:
def putdetails(self):
self.type=input("Enter Type Of Items(Type Veg/Nonveg/Both :")
if self.type=="veg":
self.no_of_items = int(input("Enter No Of Vegitems:"))
vegbiryani = int(input("Enter your Veg biryni cost :"))
vegprice=vegbiryani*self.no_of_items
split_vegprice=vegprice/res
if vegprice>=500:
veg_discount=vegprice*0.05
total_veg_price=vegprice-veg_discount
split_vegprice1 = total_veg_price / res
print("----------------------------------------------")
print("Your Choosing Item is :",self.type)
print("Your Total Payment is :", total_veg_price)
print("Your Discount is :", veg_discount)
print("Your payble amount is :", total_veg_price-veg_discount)
print("-------------------------------------------------------")
print("Indivisual bills :")
for x in lst:
print(x, "---".format(lst), "---", split_vegprice1)
else:
print("----------------------------------")
print("Your Choosing Item is :",self.type)
print("Your Total Payment is :",vegprice )
print("----------------------------------")
print("Indivisual bills :")
for x in lst:
print(x, "---".format(lst), "---", split_vegprice)
if self.type=="nonveg":
self.no_of_items=int(input("Enter No Of NonVegitems:"))
nonvegcost = int(input("Enter NonVeg biryni cost :"))
nonveg=nonvegcost*self.no_of_items
split_nonveg=nonveg/res
if nonveg>=1000:
nonveg1=nonveg*0.05
total_nonveg_price=nonveg-nonveg1
split_nonveg1=total_nonveg_price/res
print("--------------------------------------------------")
print("Your Choosing Item is :", self.type)
print("Your Total Payment is :",total_nonveg_price)
print("Your Discount is :", nonveg1)
print("Your Total Amount :", total_nonveg_price-nonveg1)
print("------------------------------------------------------")
for x in lst:
print("Indivisual Bills :")
print(x, "---".format(lst), "---", split_nonveg1)
else:
print("--------------------------------------")
print("Your Choosing Item is :",self.type)
print("Your Total Payment is :",nonveg )
print("-----------------------------------")
print("Indivisual Bills :")
for x in lst:
print(x, "---".format(lst), "---", split_nonveg)
if self.type=="both":
self.no_of_vegitems=int(input("Enter No Of VegItems:"))
vegbiryani = int(input("Enter your Veg cost :"))
vegprice = vegbiryani * self.no_of_vegitems
self.no_of_nonvegitems = int(input("Enter No Of NonVegItems:"))
nonvegcost = int(input("Enter NonVeg Cost :"))
nonveg=nonvegcost*self.no_of_nonvegitems
total_bill=vegprice+nonveg
split_totalbill=total_bill/res
if total_bill>2000:
discount=total_bill*0.10
total_cost=total_bill-discount
split_totalcost=total_cost/res
print("----------------------------")
print("No of Veg Items : ",self.no_of_vegitems)
print("Total Veg Amount is : ",vegprice)
print("--------------------------------------")
print("No Of NonVeg Items : ",self.no_of_nonvegitems)
print("Total Veg Amount is : ", nonveg)
print("-------------------------------------------")
print("Your Total Bill Without Discount : ",total_bill)
print("Your Discount is :",discount)
print("Your Total Bill After Discount(Veg+NonVeg) is :",total_cost)
print("----------------------------------------------")
for x in lst:
print(x, "---".format(lst), "---",split_totalcost )
else:
print("----------------------------")
print("No of Veg Items : ", self.no_of_vegitems)
print("Total Veg Amount is : ", vegprice)
print("--------------------------------------")
print("No of Nonveg Items : ", self.no_of_nonvegitems)
print("Total NonVeg Amount is : ", nonveg)
print("-------------------------------------------")
print("Your Total Bill Without Discount : ", total_bill)
print("------------------------------------------------")
for x in lst:
print(x, "---".format(lst), "---",split_totalbill )
else:
print("Thanks")
#calling block
#m=management()
#m.putdetails()
|
7c4b8a424c943510052f6b15b10a06a402c06f08 | prasadnaidu1/django | /Adv python practice/QUESTIONS/10.py | 845 | 4.125 | 4 | #Question:
#Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
#Suppose the following input is supplied to the program:
#hello world and practice makes perfect and hello world again
#Then, the output should be:
#again and hello makes perfect practice world
#Hints:
#In case of input data being supplied to the question, it should be assumed to be a console input.
#We use set container to remove duplicated data automatically and then use sorted() to sort the data.
str=input("enter the data :")
lines=[line for line in str.split()]
#print(" ".join(sorted(list(set((lines))))))
l1=sorted(lines)
print(l1)
l2=list(lines)
print(l2)
l3=sorted(l1)
print(l3)
l4=set(lines)
print(l4)
l5=" ".join(sorted(list(set(lines))))
print(l5) |
ee21470f4fda9757bd0e754f2b3dceb80c6fe4af | prasadnaidu1/django | /Adv python practice/ASSIGNMENT2.py | 3,046 | 3.953125 | 4 | basic_salary = float(input("Enter Your Salary : "))
class employee:
def salary(self):
tax=input("If You Have Tax Expenses Press y/Y : ")
if tax=="y":
ta=float(input("Enter How much TaxExpenses You Have(In The Form Of Percentage): "))
ta_r=ta/100
self.taxes=basic_salary*ta_r
else:
self.taxes=0
cellphone = input("If Have You CellPhone Expenses Press y/Y : ")
if cellphone=="y":
ce=float(input("Enter How much CellPhoneExpenses You Have(In The Form Of Percentage) :"))
ce_r=ce/100
self.cell_phone_expences=basic_salary*ce_r
else:
self.cell_phone_expences=0
food = input("If You Have Food Expenses Press y/Y :")
if food=="y":
fo = float(input("Enter How much FoodExpenses You Have(In The Form Of Percentage) : "))
fo_r = fo / 100
self.food_expences=basic_salary*fo_r
else:
self.food_expences=0
trans=input("If You Have Transpotation Expenses Press y/Y :")
if trans=="y":
tr = float(input("Enter How much TranpotationExpenses You Have(In The Form Of Percentage) :"))
tr_r = tr / 100
self.transpotation_expences=basic_salary*tr_r
else:
self.transpotation_expences=0
cloths = input("If You Have Cloths Expenses Press y/Y : ")
if cloths=="y":
cl = float(input("Enter How much ClothsExpenses You Have(In The Form Of Percentage) :"))
cl_r = cl / 100
self.clothing_expences=basic_salary*cl_r
else:
self.clothing_expences=0
medical=input("If You Have Medical Expenses Press y/Y :")
if medical=="y":
me = float(input("Enter How much ClothsExpenses You Have(In The Form Of Percentage) :"))
me_r = me / 100
self.medical_expences=basic_salary*me_r
else:
self.medical_expences=0
self.total_expences = self.taxes + self.cell_phone_expences + self.food_expences + self.transpotation_expences + self.clothing_expences + self.medical_expences
self.savings = basic_salary - self.total_expences
def display(self):
print("--------------------------------------------------------")
print("Your Monthly Income And Expenses")
print("Your Monthly Salary : ",basic_salary)
print("Tax Expenses :", self.taxes)
print("CellPhone Expenses :", self.cell_phone_expences)
print("Food Expenses :", self.food_expences)
print("Transpotation Expenses:", self.transpotation_expences)
print("Clothing Expenses:", self.clothing_expences)
print("Medical Expenses:", self.medical_expences)
print("Total Monthly Expenses:", self.total_expences)
print("After Expenses Your Saving Amount is:", self.savings)
print("-------------------------------------------------------------")
#calling block
emp=employee()
emp.salary()
emp.display()
|
56431060c05fe0ab91e9b1e4c6ac3939d3936b47 | prasadnaidu1/django | /Adv python practice/QUESTIONS/9.py | 474 | 4.03125 | 4 | #Question£º
#Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
#Suppose the following input is supplied to the program:
#Hello world
#Practice makes perfect
#Then, the output should be:
#HELLO WORLD
#PRACTICE MAKES PERFECT
lst=[]
while True:
str=input("enter data :")
if str:
str1=lst.append(str.upper())
else:
break
for x in lst:
print("".join(x))
|
f676db3d1fc4f349b7ddb2dec69723782cd4d1d2 | jakeloria02/Python_AI | /Main.py | 884 | 3.859375 | 4 | import requests, json
leave = {"exit", "leave", "end", "bye"}
GREETINGS = {"hello", "hey", "yo", "boi", 'hey man', 'hey boi', 'hey 117', 'hey [117]', "heyo", "heyy"}
GREETING_RESP = {"Hello", "Hey", "Hello, Sir!"}
WEATHER = {'whats the weather today?', "weather", 'whats the weather?', 'whats the weather today', 'whats the weather'}
resp = None
print("[117] Welcome back!")
print("[117] How may I help you?")
while True:
try:
resp = raw_input(">>")
except :
print("Sorry, I didnt understand that.")
continue
if resp in leave:
print("[117] Bye!")
break
elif resp in GREETINGS:
print("[117] Hello Sir!")
elif resp in WEATHER:
print("....")
import weather
else:
print("[117] sorry I dont have an answer to that question yet please try a different one!")
|
32fdb667ad72b8d13d7d844bde4491b0955165d4 | thisislsj/smart-reservation | /logicpy.py | 695 | 3.578125 | 4 | msg=["02","07","3"]
msgSimple="batman"
print("msg is ",msgSimple)
seatsAvailable=50
referencecode=5
while True:
msgInput=input("Type the msg: ")
print(msgInput)
if msgInput=="superman":
if seatsAvailable >0:
referencecode=referencecode+1
seatsAvailable=seatsAvailable-1
print(seatsAvailable)
reply="Your reference code is" , "MON", #referencecode
print(reply) #replace with send SMS method
else:
reply="No seats available"
print(reply) #replace with send SMS method
else:
reply="Your request is invalid"
print(reply)
|
570740ed8b072e0b249309b15d33f27f2b94d158 | nupur24/python- | /untitled4.py | 592 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 21 14:16:32 2018
@author: HP
"""
while True:
s = raw_input("enter string : ")
if not s:
break
if s.count("@")!=1 and s.count(".")!=1:
print "invalid"
else:
s = s.split("@")
#print s
usr = s[0]
print usr
web_ext = s[1].split(".")
print web_ext
if len(web_ext) == 2:
web,ext = web_ext
#print web
#print ext
print "valid"
else:
print "Failed"
|
47f0ab0709c616b62f4871047f350b935cc1a6e2 | nupur24/python- | /nupur_gupta_12.py | 303 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 15 12:01:08 2018
@author: HP
"""
def br():
s,b,g=a
if g%5 > s:
return False
if s+b*5 >= g:
return True
else:
return False
a=input("enter numbers:")
print br()
|
11b760a6ae93888c812d6d2912eb794d98e9c3e0 | mohadesasharifi/codes | /pyprac/dic.py | 700 | 4.125 | 4 | """
Python dictionaries
"""
# information is stored in the list is [age, height, weight]
d = {"ahsan": [35, 5.9, 75],
"mohad": [24, 5.5, 50],
"moein": [5, 3, 20],
"ayath": [1, 1.5, 12]
}
print(d)
d["simin"] = [14, 5, 60]
d.update({"simin": [14, 5, 60]})
print(d)
age = d["mohad"][0]
print(age)
for keys, values in d.items():
print(values, keys)
d["ayath"] = [2]
d.update("ayath")
# Exercises
# 1 Store mohad age in a variable and print it to screen
# 2 Add simin info to the dictionary
# 3 create a new dictionary with the same keys as d but different content i.e occupation
# 4 Update ayath's height to 2 from 1.5
# 5 Write a for loop to print all the keys and values in d
|
76b21b47b0166c5a98529751abbba6323d8aef43 | JacquesAucamp/Factorial-Digits | /JAucamp_factorial_digits.py | 2,435 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 8 12:41:16 2021
@author: User-PC
"""
import sys
#==========================================================
# CALCULATION FUNCTION
#==========================================================
def SumOfFactorialDigits(x):
digits_sum = 0
# Create array to store the numbers for the
# factorial calculation.
factorial_digits = []
factorial_digits.append(1) # adds 1 to the end
#------------------------------------------------------
# FACTORIAL CALCULATION
#------------------------------------------------------
# Calculate the factorial of the number
# ie. 10! = 1*2*3...*10
for k in range (1, x+1):
# need to only store on digit per location of
# the digit vector. Therefore must carry over the
# excess to the next location
carry_value = 0
for j in range(len(factorial_digits)):
# Calculate the leftover and the carry
# from the previous calculation
leftover = factorial_digits[j]*k + carry_value
# Store the result
carry_value = leftover//10
factorial_digits[j] = leftover%10
while (carry_value != 0):
factorial_digits.append(carry_value%10)
carry_value //= 10
#------------------------------------------------------
#------------------------------------------------------
# DIGIT SUM CALCULATION
#------------------------------------------------------
# Calculate the sum of the digits of factorial_digits[]
#------------------------------------------------------
for r in range(len(factorial_digits)):
digits_sum += factorial_digits[r]
return digits_sum
#------------------------------------------------------
#==========================================================
#==========================================================
# MAIN
#==========================================================
if __name__ == "__main__":
# Number to get factorial of
factorial_number = int(sys.argv[1])
# Main Function that calculates the sum of the factorials
sum_number = SumOfFactorialDigits(factorial_number)
print(sum_number)
#=========================================================== |
0c4c7448b192fe9f90938a8e3bceae6b10844fd8 | henrylu518/LeetCode | /Best Time to Buy and Sell Stock III.py | 1,342 | 3.828125 | 4 | """
Author: henry, henrylu518@gmail.com
Date: May 23, 2015
Problem: Best Time to Buy and Sell Stock III
Difficulty: Medium
Source: http://leetcode.com/onlinejudge#question_123
Notes:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution: dp. max profit = max profit of left + max profit of right
"""
class Solution:
# @param {integer[]} prices
# @return {integer}
def maxProfit(self, prices):
if prices == []: return 0
maxProfitLeft = [None] * len(prices)
maxProfitRight = [None] * len(prices)
minPrice, maxProfitLeft[0] = prices[0], 0
for i in xrange(1, len(prices)):
minPrice = min(minPrice, prices[i])
maxProfitLeft[i] = max( maxProfitLeft[i - 1], prices[i] - minPrice )
maxPrice, maxProfitRight[-1] = prices[-1], 0
for i in xrange(len(prices) - 2, -1, -1):
maxPrice = max(prices[i], maxPrice)
maxProfitRight[i] = max(maxProfitRight[i + 1], maxPrice - prices[i])
return max([maxProfitLeft[i] + maxProfitRight[i] for i in xrange(len(prices))]) |
e92b6ffddca5f7d7764278e8fca08da691e8da5c | henrylu518/LeetCode | /Combinations.py | 1,246 | 3.578125 | 4 | """
Author: Henry, henrylu518@gmail.com
Date: May 13, 2015
Problem: Combinations
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_77
Notes:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Solution: DFS.
"""
class Solution:
# @param {integer} n
# @param {integer} k
# @return {integer[][]}
def combine_1(self, n, k):
def combineRecur(result, current, m, remain):
if remain == 0:
result.append(current)
return
if m > 0:
combineRecur(result, [m] + current , m - 1, remain - 1)
combineRecur(result, current, m - 1, remain)
result = []
combineRecur(result,[], n, k)
return result
def combine_2(self, n, k):
def combineRecur(current, m, remain):
if remain == 0: return [current]
if m > 0:
return combineRecur( [m] + current, m - 1, remain - 1) + \
combineRecur(current, m - 1, remain)
return []
return combineRecur([], n, k )
|
f7ced0cc2205948a24e69d0aaf2ec99d2fd8a09e | henrylu518/LeetCode | /Sqrt(x).py | 735 | 3.8125 | 4 | """
Author: Henry, henrylu518@gmail.com
Date: May 13, 2015
Problem: Sqrt(x)
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_69
Notes:
Implement int sqrt(int x).
Compute and return the square root of x.
Solution: Binary search in range [0, x / 2 + 1].
There is also Newton iteration method.
"""
class Solution:
# @param {integer} x
# @return {integer}
def mySqrt(self, x):
if x < 0: return -1
low, high = 0, x
while high >= low:
middle = (high + low) / 2
if middle ** 2 == x: return middle
elif middle ** 2 > x:
high = middle - 1
else:
low = middle + 1
return high
|
a4dd4cde4800d2071a460bb53d0c8a26b1b1f4d8 | henrylu518/LeetCode | /Search Insert Position.py | 456 | 3.671875 | 4 | class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer}
def searchInsert(self, nums, target):
low, high = 0, len(nums) - 1
while low <= high:
middle = (low + high) / 2
if nums[middle] == target:
return middle
elif nums[middle] < target:
low = middle + 1
else:
high = middle - 1
return low |
66201819201c710b9bc3cb6b66eec783d1450b6b | henrylu518/LeetCode | /Remove Duplicates from Sorted List II.py | 1,139 | 3.5 | 4 | """
Author: Henry, henrylu518@gmail.com
Date: May 14, 2015
Problem: Remove Duplicates from Sorted List II
Difficulty: Easy
Source: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Notes:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Solution: iterative
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def deleteDuplicates(self, head):
dummy = ListNode(None)
dummy.next = head
previous = dummy
while head:
while head and head.next and head.val == head.next.val:
value = head.val
while head and head.val == value:
head = head.next
previous.next = head
previous = previous.next
if head: head = head.next
return dummy.next |
00da27e1e70bac78566304625fe1cec186b7a587 | henrylu518/LeetCode | /Jump Game II.py | 1,513 | 3.546875 | 4 | """
Date: May 18, 2015
Problem: Jump Game II
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_45
Notes:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Solution: Jump to the position where we can jump farthest (index + A[index]) next time.
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
def jump(self, nums):
i, reachable, step = 0, 0, 0
while reachable < len(nums) - 1:
nextReachable = reachable
while i <= reachable and i < len(nums):
nextReachable = max(i + nums[i], nextReachable)
i += 1
reachable = nextReachable
step += 1
return step
def jump_2(self, nums):
if len(nums) in [0, 1]: return 0
queue, visited = [(0, 0)], set()
while queue:
i,steps = queue.pop(0)
if i not in visited:
visited.add(i)
for j in xrange(nums[i], 0, -1):
if i + j >= len(nums) - 1:
return steps + 1
queue.append((i + j, steps + 1))
|
ce9f6b1070b57982cc521fbe9672d18fced43a58 | henrylu518/LeetCode | /Populating Next Right Pointers in Each Node.py | 1,915 | 4.0625 | 4 | """
Author: Henry, henrylu518@gmail.com
Date: May 16, 2015
Problem: Populating Next Right Pointers in Each Node
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_116
Notes:
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
Solution: 1. Iterative: Two 'while' loops.
3. Recursive: DFS. Defect: Use extra stack space for recursion.
"""
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
while root and root.left:
firstNode = root.left
while root:
root.left.next = root.right
if root.next:
root.right.next = root.next.left
root = root.next
root = firstNode
def connect_2(self, root):
if root is None:
return
if root.left:
root.left.next = root.right
if root.right and root.next:
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
|
d112900cddfe3b0bbef72efeeb697dfc6cbe86bb | zman0225/python_cryptography | /ciphers/detectEnglish.py | 1,294 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: ziyuanliu
# @Date: 2014-02-07 18:12:47
# @Last Modified by: ziyuanliu
# @Last Modified time: 2014-02-07 21:23:50
UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary():
dictionaryFile = open('dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word]=None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return float(matches)/len(possibleWords)
def removeNonLetters(message):
lettersOnly = []
for char in message:
if char in LETTERS_AND_SPACE:
lettersOnly.append(char)
return ''.join(lettersOnly)
def isEnglish(message, wordPercentage = 20, letterPer = 85):
wordsMatch = getEnglishCount(message)*100 >= wordPercentage
numLetters = len(removeNonLetters(message))
msgLetterPercentage = float(numLetters)/len(message)*100
lettersMatch = msgLetterPercentage >= letterPer
return wordsMatch and lettersMatch
|
b6ba17928cbcb5370f5d144e64353b9d0cd8fcbd | Mohsenabdn/projectEuler | /p004_largestPalindromeProduct.py | 792 | 4.125 | 4 | # Finding the largest palindrome number made by product of two 3-digits numbers
import numpy as np
import time as t
def is_palindrome(num):
""" Input : An integer number
Output : A bool type (True: input is palindrome, False: input is not
palindrome) """
numStr = str(num)
for i in range(len(numStr)//2):
if numStr[i] != numStr[-(i+1)]:
return False
return True
if __name__ == '__main__':
start = t.time()
prods = (np.reshape(np.arange(100, 1000), (1, 900)) *
np.reshape(np.arange(100, 1000), (900, 1)))[np.tril_indices(900)]
prods = np.sort(prods)[::-1]
for j in multiples:
if is_palindrome(j):
print(j)
break
end = t.time()
print('Run time : ' + str(end - start))
|
82aff3d2c7f6ad8e4de6df39d481df878a7450f7 | sree714/python | /printVowel.py | 531 | 4.25 | 4 | #4.Write a program that prints only those words that start with a vowel. (use
#standard function)
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
print("The original list is : " + str(test_list))
res = []
def fun():
vow = "aeiou"
for sub in test_list:
flag = False
for ele in vow:
if sub.startswith(ele):
flag = True
break
if flag:
res.append(sub)
fun()
print("The extracted words : " + str(res))
|
8d6df43f43f157324d5ce3012252c3c89d8ffba4 | superyaooo/LanguageLearning | /Python/Learn Python The Hard Way/gpa_calculator.py | 688 | 4.15625 | 4 | print "Hi,Yao! Let's calculate the students' GPA!"
LS_grade = float(raw_input ("What is the LS grade?")) # define variable with a string and input, no need to use "print" here.
G_grade = float(raw_input ("What is the G grade?")) # double (()) works
RW_grade = float(raw_input ("What is the RW grade?"))
Fin_grade = float(raw_input ("What is the Final exam grade?"))
# raw_input deals with string. needs to be converted into a floating point number
Avg_grade = float((LS_grade*1 + G_grade*2 + RW_grade*2 + Fin_grade*2)/7)
# the outer () here is not necessary
print ("The student's GPA is:"),Avg_grade # allows to show the variable directly
|
2de9b9b92b49f32c62e9d86b0c69985f8fb4bb85 | superyaooo/LanguageLearning | /Python/Learn Python The Hard Way/ex39.py | 1,069 | 3.953125 | 4 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
stuff = ten_things.split(' ') # need to add space between the quotation marks.
more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop() # removes and returns the last item in the list
print "Adding:", next_one
stuff.append(next_one)
print "There's %d items now." % len(stuff)
print "There we go:", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] # the last item in the list. Negative numbers count from the end towards the beginning.
print stuff.pop()
print ' '.join(stuff) # need to add space between the quotation marks to give space between print-out words. Means: join 'stuff' with spaces between them.
print '#'.join(stuff[3:5]) # extracts a "slice" from the stuff list that is from element 3 to element 4, meaning it does not include element 5. It's similar to how range(3,5) would work.
|
edfb7ae4988150d17c6fb84b68e44ecdc8d17806 | superyaooo/LanguageLearning | /Python/Learn Python The Hard Way/ex40ss.py | 322 | 3.609375 | 4 | # experiment version 2
cities = {'CA': 'San Francisco', 'MI': 'Detroit',
'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
for city in cities.items():
print "City:", city
for state,city in cities.items():
print "Places to move:", (state,city)
|
a3ae3bea53a3b19012f0b93749ac8c8aaa6a2427 | superyaooo/LanguageLearning | /Python/Learn Python The Hard Way/ex14s.py | 649 | 4.0625 | 4 | from sys import argv
script, user_name = argv
prompt = 'What you say?' # prompt could be random things. it shows up at line 9,12,15.
print "Hi,%s!%s here :)" %(user_name,script)
print "Need to ask you some questions."
print "Do you eat pork,%s?" % user_name
pork = raw_input(prompt)
print "Do you like beef?"
beef = raw_input(prompt)
print "What do you think of %s?" % user_name
username = raw_input(prompt) # if use 'user_name'to define variable here, then user_name becomes whatever you type in from now on.
print '''
Ok. So, you said %r to pork; %r to beef; and %r to %s.
''' %(pork,beef,username,user_name)
|
66ec728580a3be763105fe44f399b5f98f3c449f | AndreyAD1/18_price_format | /format_price.py | 837 | 3.640625 | 4 | import argparse
def get_console_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('price', type=float, help='Enter a price.')
arguments = parser.parse_args()
return arguments
def format_price(price):
if type(price) == bool:
return None
try:
real_num_price = float(price)
except (TypeError, ValueError):
return None
rounded_price = round(real_num_price, 2)
if rounded_price.is_integer():
formatted_price = '{:,.0f}'.format(rounded_price).replace(',', ' ')
else:
formatted_price = '{:,}'.format(rounded_price).replace(',', ' ')
return formatted_price
if __name__ == '__main__':
console_arguments = get_console_arguments()
price = console_arguments.price
formatted_price = format_price(price)
print(formatted_price)
|
62d2ca63e780982a75df63ebba2853fa1a3de150 | TylerGarlick/intermediate-python-course | /my_list.py | 218 | 3.5625 | 4 | def main():
r = [4, -2, 10, -18, 22]
print(r[2:6])
print(f'len list of {r[-1]}')
t = r.copy()
print(f'is t the same as r? {t is r}')
c = r[:]
print(f'is t the same as r? {t is c}')
main()
|
5476eab2b0b2834ebb789d623703fdded5e4fa3e | RomarioGit/AED_1 | /AED26.py | 1,351 | 4 | 4 |
class aluno:
def __init__(self,nome,cpf,nota):
self.nome = nome
self.cpf = cpf
self.nota = nota
def get_nota(self):
if not self.nota == 0:
return True
return False
def cadastrar_aluno(lista_alunos):
nome = input("Informe o nome: ")
cpf = input("Informe o CPF: ")
nota = float(input("Informe a Nota: "))
alunos = aluno(nome,cpf,nota)
lista_alunos.append(alunos)
lista_alunos = []
def listar_alunos(lista_alunos):
for i in range(len(lista_alunos)):
print('Aluno:{}'.format(i))
print("Nome:{}".format(lista_alunos[i].nome))
print("CPF:{}".format(lista_alunos[i].cpf))
if lista_alunos[i].get_nota():
print("Nota: {}".format(lista_alunos[i].nota))
def menu():
print("-----MENU------")
print("1-Cadastrar Aluno;")
print('2-Analisar Nota;')
print("3-Listar Alunos;")
print("4-Sair;")
def main():
while True:
menu()
op = input("Opção>> ")
if op == '1':
cadastrar_aluno(lista_alunos)
elif op == '2':
analisa_nota(lista_alunos)
elif op == '3':
listar_alunos(lista_alunos)
elif op == '4':
print("Saindo do sistema...")
break
else:
print("Opção inválida!")
main() |
15e2d34d87b113c8f3b48ae4e0478541f8af8960 | chrisesharp/aoc-2018 | /day25/constellation.py | 1,682 | 3.609375 | 4 | import sys
def find_constellations(input):
points = {}
for line in input.split():
point = tuple(map(int, line.split(',')))
assimilated = False
linked = {}
for known_point in list(points.keys()):
if close_enough(known_point, point):
points, linked = assimilate(point, known_point, points, linked)
assimilated = True
if not assimilated:
points[point]=set(point)
if linked:
linked_constellations = list(linked.items())
first_point, constellation = linked_constellations.pop()
for other_point, other_constellation in linked_constellations:
constellation |= other_constellation
points[other_point]=first_point
return list(filter(lambda x: isinstance(x, set), points.values()))
def find_constellation(entry, points):
if isinstance(points[entry], set):
return points[entry], entry
return find_constellation(points[entry], points)
def assimilate(point, known_point, points, links):
entry, idx_pt = find_constellation(known_point, points)
entry.add(point)
points[point] = idx_pt
if entry not in links.values():
links.update({idx_pt: entry})
return points, links
def close_enough(A,B):
(x1,y1,z1,t1) = A
(x2,y2,z2,t2) = B
return abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(t1-t2) <= 3
def main(file):
with open(file, 'r') as myfile:
input = myfile.read()
constellations = find_constellations(input)
print("No. of constellations: ", len(constellations))
if __name__ == "__main__":
main(sys.argv[1])
|
9789e52489b57ddc65791d841e5f693c0e3924a4 | selinali2010/hello-world | /oneRoundYahtzee.py | 1,685 | 3.921875 | 4 | from random import choice
rolls = {
0:"None",
1: "Pair",
2: "Two Pairs",
3: "Three of a kind",
4: "Four of a kind",
5: "Yahtzee!",
6: "Full House",
7: "Large Straight"
}
dice = []
for x in range(5):
dice.append(choice([1,2,3,4,5,6]))
print "Dice %i: %i" % (x + 1, dice[x])
#find the number of repeated numbers in the roll
def numOfRepeats(dice):
repeats = [0,0,0,0,0,0] # each rep. one number (1-6)
for x in dice: #loop through the dice values
repeats[x-1] += 1 #add one to repeats for that number
return repeats
#find the number of groups of repeats in the roll (ex: 2:2 means 2 numbers are doubled aka 2 pairs)
def numOfGroups(repeats):
groups = {1:0, 2:0, 3:0, 4:0, 5:0} # keys are the number of repeats, values are the number of each group of repeats
for x in repeats: #loop through the number of repeats
if (x != 0): #as long as a number is repeated
groups[x] += 1 #add one to the value under the appropriate key
return groups
def rollResults(dice, groups, rolls):
dice.sort() #sort helps with straights
if groups[5] == 1: #if a Yahzee
return rolls[5]
elif groups[4] == 1: #four of a kind
return rolls[4]
elif groups[3] == 1 and groups[2] == 1: #Full house(1 group of 3, 1 group of 2)
return rolls[6]
elif groups[3] == 1: #three of a kind
return rolls[3]
elif groups[2] == 2: #two pairs
return rolls[2]
elif groups[2] == 1: #one pair
return rolls[1]
else: #when no repeats exist
if dice[4] == 5 or dice[0] == 2:
return rolls[7] # straight of 1,2,3,4,5 or 2,3,4,5,6
else:
return rolls[0] # no pattern
print rollResults(dice, numOfGroups(numOfRepeats(dice)), rolls)
|
44f8726cd570bf4339a767dde3e62713463da2b5 | Vladyslav92/Python_HW | /lesson_6/4_task.py | 378 | 3.828125 | 4 | # Поиск минимума с переменным числом аргументов в списке.
# def min(*args): ....
enter = [10, 20, 35, 5, 6, 2, 7, 15]
def min(*args):
base_list = args
sorted_list = []
for i in base_list:
for j in i:
sorted_list.append(j)
result = sorted(sorted_list)
return result[0]
print(min(enter))
|
86902979397a947dd5d85874129c8d1aab949ac6 | Vladyslav92/Python_HW | /lesson_2/3_task.py | 536 | 4.21875 | 4 | # На ввод подается строка. Нужно узнать является ли строка палиндромом.
# (Палиндром - строка которая читается одинаково с начала и с конца.)
enter_string = input('Введите строку: ').lower()
lst = []
for i in enter_string:
lst.append(i)
lst.reverse()
second_string = ''.join(lst)
if second_string == enter_string:
print('Это Палиндром!')
else:
print('Это не Палиндром!')
|
3de9c9f7af71fd66a0b8336e9c0a4fdcbf538973 | Vladyslav92/Python_HW | /lesson_7/2_task.py | 616 | 3.625 | 4 | # Реализовать примеры с functools - wraps и singledispatch
from functools import singledispatch, wraps
def dec_function(func):
"""Function in function"""
@wraps(func)
def wrapps():
"""decorated function"""
pass
return wrapps
@dec_function
def a_function():
"""Simple Function"""
return 'Hello World!'
@singledispatch
def summer(a, b):
pass
@summer.register(str)
def _(a, b):
print(a + b)
@summer.register(int)
def _(a, b):
print(a - b)
summer('Hello', 'World!')
summer(100, 50)
print(a_function.__name__)
print(a_function.__doc__)
|
1f84a5ede2aa4aa8d8fea4921dc1bc53e66e9d91 | Vladyslav92/Python_HW | /lesson_11/3_task.py | 1,024 | 4 | 4 | # Реализовать класс который будет:
# 3.a читать из ввода строку
# 3.b проверять, что строка состоит только из скобочек “{}[]()<>”
# 3.c проверять, что строка является правильной скобочной последовательностью - выводить вердикт
class Brackets:
def __init__(self):
self.line = input('Enter a string: ')
def read_lines(self):
return self.line
def check_elements(self):
while '()' in self.line or '[]' in self.line or '{}' in self.line or '<>' in self.line:
self.line = self.line.replace('()', '')
self.line = self.line.replace('[]', '')
self.line = self.line.replace('{}', '')
self.line = self.line.replace('<>', '')
return not self.line
TEXT = Brackets()
print(TEXT.read_lines())
print(TEXT.check_elements())
|
6cefa99cdb92c9ed5738d4a40855a78b22e23b1b | Vladyslav92/Python_HW | /lesson_8/1_task.py | 2,363 | 4.34375 | 4 | # mobile numbers
# https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem
# Let's dive into decorators! You are given mobile numbers.
# Sort them in ascending order then print them in the standard format shown below:
# +91 xxxxx xxxxx
# The given mobile numbers may have +91, 91 or 0 written before the actual digit number.
# Alternatively, there may not be any prefix at all.
# Input Format
# The first line of input contains an integer, the number of mobile phone numbers.
# lines follow each containing a mobile number.
# Output Format
# Print mobile numbers on separate lines in the required format.
#
# Sample Input
# 3
# 07895462130
# 919875641230
# 9195969878
#
# Sample Output
# +91 78954 62130
# +91 91959 69878
# +91 98756 41230
def phones_fixer(func):
def wrapper(nlist):
result_list = []
for numbr in nlist:
result = list(numbr)
if '+91' in numbr:
if 10 < len(numbr) < 12:
result.insert(3, ' ')
result.insert(-5, ' ')
else:
return 'The number is not correct'
elif len(numbr) == 11:
result.insert(0, '+')
result.insert(1, '9')
result.insert(2, '1')
result.insert(3, ' ')
result.remove(result[4])
result.insert(-5, ' ')
elif len(numbr) == 12:
result.insert(0, '+')
result.insert(3, ' ')
result.insert(-5, ' ')
elif len(numbr) == 10:
result.insert(0, '+')
result.insert(1, '9')
result.insert(2, '1')
result.insert(3, ' ')
result.insert(-5, ' ')
else:
return 'The number is not correct'
result_list.append(''.join(result))
return func(result_list)
return wrapper
@phones_fixer
def sort_numbers(numbers_list):
return '\n'.join(sorted(numbers_list))
def read_numbers():
n = int(input('Количество номеров: '))
numbers = []
for i in range(n):
number = input('Введите номер: ')
numbers.append(number)
return numbers
if __name__ == '__main__':
numbers = read_numbers()
print(sort_numbers(numbers))
|
d2f3d3b79ad81c34394ed3cfa336b07f5edaceff | viniandrd/Biodiesel-Simulator | /utils/logginprinter.py | 656 | 3.625 | 4 | import sys
class LoggingPrinter:
def __init__(self, filename):
self.out_file = open(filename, "w")
self.old_stdout = sys.stdout
# this object will take over `stdout`'s job
sys.stdout = self
# executed when the user does a `print`
def write(self, text):
self.old_stdout.write(text)
self.out_file.write(text)
# executed when `with` block begins
def __enter__(self):
return self
# executed when `with` block ends
def __exit__(self, type, value, traceback):
# we don't want to log anymore. Restore the original stdout object.
sys.stdout = self.old_stdout
|
3f5e5c7307e293db831a422f71e762d559edee95 | saravey2021/homework-week-11 | /Homework week 11/fri2.py | 347 | 3.96875 | 4 | def getPrice(fruitName):
if fruitName=="banana":
return 2
if fruitName=="apple":
return 5
if fruitName=="orange":
return 1
print("banana price is:"+str(getPrice("banana"))+" dolars")
print("Orange price is:"+str(getPrice("orange"))+" dolars")
print("apple price is:"+str(getPrice("apple"))+" dolars")
|
1ac6e401e05a22f94610ceb0e2aee0d7350cd3c2 | Zoranc1/boggle | /boggle.py | 2,220 | 3.5625 | 4 | from string import ascii_uppercase
from random import choice
def make_grid(colums,rows):
return { (c,r) : choice(ascii_uppercase)
for r in range(rows)
for c in range(colums)}
def potencial_neighbours(position):
c, r = position
return[(c-1,r-1),(c,r-1),(c+1,r-1),
(c-1,r), (c+1,r ),
(c-1,r+1),(c,r+1),(c+1,r+1)]
def path_to_word(path,grid):
word =""
for position in path:
word += grid[position]
return word
def load_word_list(filename):
with open(filename) as f:
text = f.read().upper().split("\n")
return set(text)
def get_real_neighbours(grid):
real_neighbours ={}
for position in grid:
pn = potencial_neighbours(position)
on_the_grid=[p for p in pn if p in grid]
real_neighbours[position] = on_the_grid
return real_neighbours
def is_a_real_word(word,dictionary):
return word in dictionary
def get_stems(word):
return [word[:i] for i in range(1, len(word))]
def get_stems_for_word_list(wl):
stems = []
for word in wl:
stems_for_word = get_stems(word)
stems += stems_for_word
return set(stems)
def search(grid, dictionary):
neighbours = get_real_neighbours(grid)
stems = get_stems_for_word_list(dictionary)
words = []
def do_search(path):
word = path_to_word(path, grid)
if is_a_real_word(word,dictionary):
words.append(word)
if word in stems:
for next_pos in neighbours[path[-1]]:
if next_pos not in path:
do_search(path + [next_pos])
for position in grid:
do_search([position])
return set(words)
def display_words(words):
for word in words:
print(word)
print("Found %s words" % len(words))
def main():
grid = make_grid(200, 200)
word_list = load_word_list("words.txt")
words = search(grid, word_list)
display_words(words)
main()
|
3aa3b572f2561c795397cc40a3ee0e6eb522f036 | pranavvm26/RandomProblemCodes | /find_longest_palindrome.py | 1,488 | 4.09375 | 4 | import copy
palindrome_list = []
def find_palindrome(palindrome_string):
longest_current_palin = 0
list_p = list(palindrome_string)
for i in range(2, len(list_p), 1):
duplicate_string = copy.deepcopy(list_p)
del duplicate_string[0:i]
_set = list_p[0:i]
res = "".join(_set) in "".join(duplicate_string)
if res:
longest_current_palin = _set
#print(res, " with word ", "".join(_set))
if longest_current_palin != 0:
print("The longest palindrome word in the current session is ", "".join(longest_current_palin))
return palindrome_string.replace("".join(longest_current_palin), ""), "".join(longest_current_palin)
else:
return "", ""
if __name__ == "__main__":
palindrome_string = input("Enter the string to find the palindrome from:")
palindrome_string_modified, longest_palindrome_word = find_palindrome(palindrome_string)
palindrome_list.append(longest_palindrome_word)
while True:
palindrome_string_modified, longest_palindrome_word = find_palindrome(palindrome_string_modified)
palindrome_list.append(longest_palindrome_word)
if len(list(palindrome_string_modified)) == 0:
break
if palindrome_list[0] != "":
print("The longest palindrome words in the string are as follows :")
for strings in palindrome_list:
print(strings)
else:
print("No palindrome words in the given string")
|
66d4bc1aec1f41337454123409ef597b1ea9ae8d | timmywilson/pandas-practical-python-primer | /training/level-1-the-zen-of-python/dragon-warrior/peppy.py | 836 | 4 | 4 | """
This code (which finds the sume of all unique multiples of 3/5 within a
given limit) breaks a significant number of PEP8 rules. Maybe it doesn't even
work at all.
Find and fix all the PEP8 errors.
"""
import os
import sys
import operator
INTERESTED_MULTIPLES = [3, 5] # constants should be all caps with underscores
def quicker_multiple_of_three_and_five(top_limit):
multiplier = 1
multiples = set()
while True:
if multiplier * 5 < top_limit:
multiples.add(multiplier * 5)
if multiplier * 3 < top_limit:
multiples.add(multiplier * 3)
else:
break
multiplier += 1
return sum(multiples)
print("The sum of all unique multiples of 3 and 5 which given an "
"upper limit of X is to consider is: answer")
|
554db1fd0a01073381a9877a33c4d1859e6e2915 | maralex2003/OlistDojo1 | /dojo/ativ_1e2/categories.py | 1,114 | 3.5 | 4 | class Category:
def __init__(self, id: int, name: str):
self.__id = id
self.__name = name
def set_id(self, id: int) -> None:
self.__id = int(id)
def get_id(self) -> int:
return self.__id
def set_name(self, name: str) -> None:
self.__name = name
def get_name(self) -> str:
return self.__name
def __str__(self):
return f"""
Id: {self.get_id()}
Name: {self.get_name()}
"""
class SubCategory(Category):
def __init__(self, id: int, name: str, parent: Category):
self.__parent = parent
super().__init__(id, name)
def get_parent(self) -> Category:
return self.__parent
def set_parent(self, parent: Category) -> None:
self.__parent = parent
def get_parent_name(self) -> str:
return self.get_parent().get_name()
def __str__(self):
return f"""
Id: {self.get_id()}
Name: {self.get_name()}
Mother: {self.get_parent_name()}
"""
|
68ece26086a0fdc492e49949c1ca30df1a784ec2 | maralex2003/OlistDojo1 | /aula016/05_assert_classes.py | 1,304 | 4.09375 | 4 | # Com assert podemos testar as classes e seus métodos
# podendo verificar objetos da classe e
# o resultado de seus comportamentos
class Product:
def __init__(self, name:str, price:float)->None:
self.name = name
self.price = price
@property
def name(self)->str:
return self.__name
@property
def price(self)->float:
return self.__price
@name.setter
def name(self, name:str)->None:
self.__name = name
@price.setter
def price(self, price:float)->None:
try:
self.__price = float(price)
except ValueError as e:
raise ValueError('O valor nao pode ser convertido para float') from e
nome = 'Comp'
preco = 2000
prod1 = Product(nome, preco)
# testando se o objeto da classe é do tipo esperado e assim tentando o construtor
assert type(prod1) == Product
assert isinstance(prod1, Product)
# testando o get e o set de name
assert prod1.name == nome
assert type(nome) == type(prod1.name)
assert prod1.name is nome
# testando o get e o set de price
assert prod1.price == preco
assert isinstance(prod1.price, float)
# testando se a exceção é gerada pelo setter do price
preco = 'R$2000'
try:
prod1.price = preco
except Exception as e:
assert isinstance(e, ValueError)
|
b19a1447ed25ec4da8414b703a3aa433394eeb36 | charliesan16/Python-Estudio-Propio | /cantidadFilasPiramide.py | 226 | 3.9375 | 4 | bloques = int(input("Ingrese el número de bloques de la piramide:"))
altura=0
while bloques:
altura=altura+1
bloques=bloques-altura
if bloques <= altura:
break
print("La altura de la pirámide:", altura)
|
b6a922d94e92769c5ab73e7fa0bb9d200147e17b | charliesan16/Python-Estudio-Propio | /Hola Mundo.py | 146 | 3.6875 | 4 | def suma(a,b):
return a+b
a=int(input("ingrese el valor de a="))
b=int(input("ingrese el valor de b="))
s=suma(a,b)
print("La suma es de=",s)
|
46bc1461ea1fa5794bfc6ec29b021550c54dc7d0 | Ashutoshcoder/python-codes | /Aggregation/groupAccordingToStateAndMatching.py | 1,741 | 3.78125 | 4 | """
Author : Ashutosh Kumar
Version : 1.0
Description : Grouping according to state and then finding state with population >100
Then we are finding the biggest city and smallest city in the State.
Email : ashutoshkumardbms@gmail.com
"""
import pymongo
import pprint
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['aggregation']
mycol = mydb['population']
result = mydb.population.insert_many(
[
{"_id": 1, "city": "Pune", "state": "MH", "pop": 68},
{"_id": 2, "city": "Mumbai", "state": "MH", "pop": 240},
{"_id": 3, "city": "Nashik", "state": "MH", "pop": 22},
{"_id": 4, "city": "Nagour", "state": "MH", "pop": 28},
{"_id": 5, "city": "Bhopal", "state": "MP", "pop": 30},
{"_id": 6, "city": "Indore", "state": "MP", "pop": 45}
]
)
# sum and then a condition(similar to having SQL having clause
myOutput = mydb.population.aggregate(
[
{"$group": {"_id": "$state", "totalPop": {"$sum": "$pop"}}},
{"$match": {"totalPop": {"$gte": 100}}}
]
)
for doc in myOutput:
pprint.pprint(doc)
# least and most populated city in each state
myOutput = mydb.population.aggregate(
[
{
"$group":
{
"_id": {"state": "$state", "city": "$city"},
"pop": {"$sum": "$pop"}
}
},
{"$sort": {"pop": 1}},
{"$group":
{
"_id": "$_id.state",
"biggestCity": {"$last": "$_id.city"},
"biggestPop": {"$last": "$pop"},
"smallestCity": {"$first": "$_id.city"},
"smallestPop": {"$first": "$pop"}
}
}
]
)
for doc in myOutput:
pprint.pprint(doc)
|
ce2e70a9d3734bacde1fd864de4ade2c53734d17 | Ashutoshcoder/python-codes | /user_nobash.py | 769 | 3.671875 | 4 | '''
Author : Ashutosh Kumar
PRN : 19030142009
Assignment: Read all the usernames from the /etc/passwd file and list users
which do not have bash as their default shell
'''
fp = ""
try:
# opening file in read mode
fp = open('/etc/passwd', 'r')
# extracting every user from the file
for line in fp:
# writing it to the new file
if 'bash' not in line:
print(line.split(':')[0])
except FileNotFoundError:
print("File not Found ")
except FileExistsError:
print("File Already Exists")
except PermissionError:
print("Permissison to open file is not granted ")
except IsADirectoryError:
print("It is a directory")
finally:
try:
fp.close()
except AttributeError:
print("File not opened ")
|
530bfb68b165b1948f17c85ad7853059150d4806 | Ashutoshcoder/python-codes | /Mongo-Example-Implementation/Bank/employeeManager.py | 2,770 | 3.609375 | 4 | '''
Author : Ashutosh Kumar
Version : 1.0
Description : Creating a Employee Management Functions(Insert,Update,Delete)
Email : ashutoshkumardbms@gmail.com
'''
import sys
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['empolyeedata']
mycol = mydb['employees']
def main():
while 1:
# select option to do CRUD operation
selection = input('\n Select 1 to insert, 2 to update, 3 to read, 4 to delete , 5 to exit \n')
if selection == '1':
insert()
elif selection == '2':
update()
elif selection == '3':
read()
elif selection == '4':
delete()
elif selection == '5':
print('Exiting ... ')
sys.exit()
else:
print('\n Invalid Selection \n')
# Function to insert data
def insert():
try:
employeeId = input('Enter Employee id : ')
employeeName = input('Enter Name : ')
employeeAge = input('Enter age :')
employeeCountry = input('Enter Country :')
mydb.employees.insert_one(
{
"id": employeeId,
"name": employeeName,
"age": employeeAge,
"country": employeeCountry
}
)
print("\n Inserted Data Successfully \n")
except ValueError:
print("Invalid Value")
except TypeError:
print("Invalid Type ")
# Function to read values
def read():
try:
empcol = mydb.employees.find()
print('\n All data from EmployeeData Database \n')
for emp in empcol:
print(emp)
except ValueError:
print("Invalid Value")
except TypeError:
print("Invalid Type ")
# Function to update a record
def update():
try:
criteria = input('\n Enter id to update \n')
name = input('\n Enter Name to update : \n')
age = input('\nEnter age to update: \n')
country = input('\nEnter Country to update :\n')
mydb.employees.update_one(
{"id": criteria},
{
"$set": {
"name": name,
"age": age,
"country": country
}
}
)
print("\n Record Updated successfully \n")
except ValueError:
print("Invalid Value")
except TypeError:
print("Invalid Type ")
# Function to delete record
def delete():
try:
criteria = input('\n Enter id to update \n')
mydb.employees.delete_one({"id": criteria})
print("\n Deletion successfully \n")
except ValueError:
print("Invalid Value")
except TypeError:
print("Invalid Type ")
if __name__ == '__main__':
main()
|
2c9d97b447fc0a3aaf464660c88ac4b9264023e7 | Ashutoshcoder/python-codes | /data-science/barGraph.py | 518 | 3.5 | 4 | """
Author : Ashutosh Kumar
Version : 1.0
Description : Plotting bar graph in Python
Email : ashutoshkumardbms@gmail.com
"""
import numpy as np
import matplotlib.pyplot as plt
city = ["Delhi", "Beijing", "Washingtion", "Tokyo", "Moscow"]
pos = np.arange(len(city))
Happiness_index = [60, 40, 70, 65, 85]
plt.bar(pos, Happiness_index, color='blue', edgecolor='black')
plt.xticks(pos, city)
plt.xlabel('City', fontsize=16)
plt.ylabel('Happiness_index', fontsize=16)
plt.title('Barchart - Happiness Index across cities', fontsize=20)
plt.show()
|
2d9c35e286e33a57bb0a441324fa16fc1c9f9793 | kozl-ek/module_0 | /Kozlova.EV_1.py | 2,018 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
import numpy as np
number = np.random.randint(1,100) # загадали число от 1 до 100
print ("Загадано число от 1 до 100")
def change(a): #Задаем функцию, изменяющую размер шага. Размер шага не должен быть меньше одного, чтобы избежать зацикливания.
if a!=1:
a=a//2
return(a)
def game_core_v1(number): #Задаем функцию,которая будет фиксировать число попыток угадать число
thinknumber=50 # задаем число, с которым будем сравнивать число, которое загадал компьютер. Выбрала 50, потому что это ровно середина
step=25 # устанавливаем размер шага- число, на которое мы будем менять thinknumber в зависимости от результата сравнения.
i=0 # устанавливаем счетчик итераций
while number!=thinknumber :
i+=1
if number>thinknumber:
thinknumber+=step
step=change(step)
elif number<thinknumber:
thinknumber-=step
step=change(step)
return(i)
def score_game(game_core):
#Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число
count_ls = []
np.random.seed(1) # фиксируем RANDOM SEED, чтобы ваш эксперимент был воспроизводим!
random_array = np.random.randint(1,100, size=(1000))
for number in random_array:
count_ls.append(game_core(number))
score = np.mean(count_ls)
print(f"Ваш алгоритм угадывает число в среднем за {score} попыток")
return(score)
score_game(game_core_v1)
|
89d6646ac4c27cbd605a3c4d3459eb2762875229 | ezefranca/hackerrank-30-days | /day6/day6.py | 368 | 3.65625 | 4 | #!/bin/python3
import sys
n = int(input().strip())
strings = []
for i in range(0, n):
string = input().strip()
strings.append(string)
arr = list(strings[i])
odd = []
even = []
for j in range(0, len(arr)):
if j % 2 == 0:
even.append(arr[j])
else:
odd.append(arr[j])
print(''.join(even),''.join(odd))
|
3d2c01cd94f0aea380e3dd5605d501ab44a5fbaf | TR18052000/DAY-3-ASSIGNMENT | /list.py | 159 | 3.75 | 4 | list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10
print(list)
list[1:3] = [89, 78]
print(list)
list[-1] = 25
print(list)
|
0f65ea15f4845b8b3e5f5117af59444a5a666cbe | thomaskost17/QHWSDGNCB | /src/models/lorenz.py | 1,169 | 3.671875 | 4 | '''
File: lorenz.py
Author: Thomas Kost
Date: 08 August 2021
@breif function for lorenz chaotic system, and plotting script
'''
import numpy as np
import matplotlib.pyplot as plt
def lorenz(x :np.array, beta: np.array)->np.array:
'''
x: position state vector of lorenz system
beta: vector of lorenz parameters
return: derivative of state vector
'''
dx = np.array([ beta[0]*(x[1]-x[0]),
x[0]*(beta[1]-x[2])-x[1],
x[0]*x[1]-beta[2]*x[2]])
return dx
def step_lorenz(x:np.array, beta:np.array, dt:float)->np.array:
next_x = x + lorenz(x,beta)*dt
return next_x
if __name__ == "__main__":
dt = 0.001
t = np.arange(0,50,dt)
x = np.zeros((3,len(t)))
x_0 = np.array((0,1,20))
b = np.array((10,28,8/3.0))
for i in range(len(t)):
if(i == 0):
x[:,i] = x_0
else:
x[:,i] = step_lorenz(x[:,i-1],b,dt)
ax = plt.figure().add_subplot(projection='3d')
ax.plot(x[0,:], x[1,:], x[2,:], lw=0.5)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Lorenz Attractor")
plt.show()
|
466900753c34afb3fb85f7a23563005515d2cd78 | jacobdanovitch/COMP1005_TA_Portal | /solutions/a4/soln.py | 3,269 | 3.578125 | 4 | #Author: Andrew Runka
#Student#: 100123456
#This program contains all of the solutions to assignment 4, fall2018 comp1005/1405
#and probably some other scrap I invented along the way
def loadTextFile(filename):
try:
f = open(filename)
text = f.read()
f.close()
return text
except IOError:
print(f"File {filename} not found.")
return ""
def countWords(filename):
text = loadTextFile(filename)
text = text.split()
return len(text)
def countCharacters(filename):
text = loadTextFile(filename)
return len(text)
def countCharacter(text,key):
count=0
for c in text:
if c==key:
count+=1
return count
def countSentences(filename):
text = loadTextFile(filename)
count = 0
count+=countCharacter(text,'.')
count+=countCharacter(text,'?')
count+=countCharacter(text,'!')
return count
#return text.count(".")+text.count('?')+text.count('!') #also valid
def removePunctuation(text):
text = text.replace(".","")
text = text.replace(",","")
text = text.replace("!","")
text = text.replace("?","")
text = text.replace(";","")
text = text.replace("-","")
text = text.replace(":","")
text = text.replace("\'","")
text = text.replace("\"","")
return text
def wordFrequency(filename):
text = loadTextFile(filename)
text = removePunctuation(text.lower())
d = {}
for w in text.split():
if w not in d:
d[w]=1
else:
d[w]+=1
return d
def countUniqueWords(filename):
dict = wordFrequency(filename)
return len(dict.keys())
def countKWords(filename,k):
dict = wordFrequency(filename)
count=0
for key in dict.keys():
if key[0] == k:
count+=1
return count
def kWords(filename,k):
dict = wordFrequency(filename)
result = []
for word in dict.keys():
if word[0] == k:
result.append(word)
return result
def longestWord(filename):
text = loadTextFile(filename)
text = removePunctuation(text).split()
longest = ""
for w in text:
if len(w)>len(longest):
longest=w
return longest
def startingLetter(filename):
dict = wordFrequency(filename)
#letters = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0} #26 counters, one for each letter
letters = {}
#count frequencies
for key in dict:
if key[0] in letters:
letters[key[0]] +=1
else:
letters[key[0]] = 1
#find largest
largest='a'
for key in letters.keys():
if letters[key]>letters[largest]:
largest=key
return largest
def letterFrequency(filename):
text = loadTextFile(filename)
d = {}
for c in text:
if c in d:
d[c]+=1
else:
d[c]=1
return d
def followsWord(filename, keyWord):
keyWord = keyWord.lower()
text = loadTextFile(filename)
text = removePunctuation(text).lower()
text = text.split()
follows = []
for i in range(len(text)-1):
if text[i] == keyWord:
if text[i+1] not in follows:
follows.append(text[i+1])
return follows
def writeLines(filename,list):
file = open(filename,'w')
#out = "\n".join(list)
out = ""
for line in list:
out+=line+"\n"
file.write(out)
file.close()
def reverseFile(filename):
text = loadTextFile(filename) #or readlines
text = text.split("\n")
text.reverse()
writeLines("reversed_"+filename, text)
|
781fc5a0241560371636b46c096d0a476fce622d | henrypalacios/transactions_account | /backend_api/src/foundation/write_lock.py | 1,196 | 3.875 | 4 | from threading import Thread, Condition, current_thread, Lock
class ReadersWriteLock:
""" A lock object that allows many simultaneous "read locks", but
only one "write lock." """
def __init__(self):
self._read_ready = Condition(Lock())
self._readers = 0
def acquire_read_lock(self):
""" Acquire a read lock. Blocks only if a thread has
acquired the write lock. """
self._read_ready.acquire()
try:
self._readers += 1
finally:
self._read_ready.release()
def release_read_lock(self):
""" Release a read lock. """
self._read_ready.acquire()
try:
self._readers -= 1
if not self._readers:
self._read_ready.notifyAll( )
finally:
self._read_ready.release( )
def acquire_write_lock(self):
""" Acquire a write lock. Blocks until there are no
acquired read or write locks. """
self._read_ready.acquire( )
while self._readers > 0:
self._read_ready.wait( )
def release_write_lock(self):
""" Release a write lock. """
self._read_ready.release( )
|
90be014b94c2b6a63f759e191759412965cc0acd | ModelPhantom/raspberrypython | /pygametest/hellopython.py | 367 | 3.59375 | 4 | import pygame
width=640
height=480
radius=100
stroke=1
pygame.init()
window=pygame.display.set_mode((width,height))
window.fill(pygame.Color(255,255,255))
while True:
pygame.draw.circle(window,pygame.Color(255,0,0),(width/2,height/2),radius,stroke)
pygame.display.update()
if pygame.QUIT in [e.type for e in pygame.event.get()]:
Break
|
0b40c91c5a9f2316d0bb16155a00f77857d74df1 | soporte00/python_practice | /01_vacattion_system_for_rappi_employees.py | 2,172 | 3.703125 | 4 | import os
'''
sections
key section
1 A. clientes
2 Logística
3 Gerencia
employees
key time(years) vacations(days)
1 1 6
1 2-6 14
1 7 20
2 1 7
2 2-6 15
2 7 22
3 1 10
3 2-6 20
3 7 30
'''
while True:
os.system("clear")
print("**********************************************")
print("* Sistema vacacional para empleados de rappi *")
print("********************************************** \n")
name = input("Ingresa el nombre del empleado: ")
print("\n1)A. clientes 2)Logística 3)Gerencia ")
employeeKey = int( input("\nIngresa el número correspondiente a su departamento: ") )
employeeYears = int( input("\nIngresa la antiguedad en años: ") )
print("\nLos datos ingresados son: \n",f"\n Nombre: {name}",f"\n Departamento: {employeeKey}",f"\n antiguedad: {employeeYears} años" )
agree = input("\n¿Los datos son correctos? escribe si o no: ")
if agree == 'si':
print("\n==================================\n")
if employeeKey == 1:
if employeeYears == 1:
print(name+" tiene 6 dias de vacaciones")
elif employeeYears >= 2 and employeeYears <=6:
print(name+" tiene 14 dias de vacaciones")
elif employeeYears >= 7:
print(name+" tiene 20 dias de vacaciones")
else:
print("La antiguedad es incorrecta")
elif employeeKey == 2:
if employeeYears == 1:
print(name+" tiene 7 dias de vacaciones")
elif employeeYears >= 2 and employeeYears <=6:
print(name+" tiene 15 dias de vacaciones")
elif employeeYears >= 7:
print(name+" tiene 22 dias de vacaciones")
else:
print("La antiguedad es incorrecta")
elif employeeKey == 3:
if employeeYears == 1:
print(name+" tiene 10 dias de vacaciones")
elif employeeYears >= 2 and employeeYears <=6:
print(name+" tiene 20 dias de vacaciones")
elif employeeYears >= 7:
print(name+" tiene 30 dias de vacaciones")
else:
print("La antiguedad es incorrecta")
else:
print("\nEl departamento elegido no es correcto")
action = input('\n ** Para repetir el programa presiona Enter o "q" para salir: ')
if action == 'q':
break |
57c4893c2f0db4ad531c725146b92b5ee066f7ed | bmoser12/608-mod3 | /custom-object.py | 473 | 3.78125 | 4 | #use this to figure out a bill total including tip and tax
def tip_amount(total,tip_percent):
return total*tip_percent
def tax_amount(total, tax_percent):
return total*tax_percent
def bill_total(total,tax,tip):
return total+tip_amount+tax_amount
total = 100
tip_percent = .20
tax_percent = .075
tax = tax_amount(total,tax_percent)
tip = tip_amount(total,tip_percent)
print('Tip amount:',tip)
print('Tax amount:', tax)
print('Bill total:',total+tax+tip)
|
d21033c6e4ba17697dcbdf20072ab069d3e4779c | imrehg/coderloop | /missile/python/missile | 1,760 | 3.84375 | 4 | #!/usr/bin/python
import sys
def findlongest(nums):
"""
Dynamic programming: O(n^2)
based on:
http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence#Dynamic_Programming
"""
n = len(nums)
if n == 0:
return 0
length = [1]*n
path = range(n)
for i in xrange(1, n):
for j in xrange(0, i):
if (nums[i] > nums[j]) and (length[i] < (length[j]+1)):
length[i] = length[j] + 1
path[i] = j
return max(length)
def findlongest2(nums):
"""
Clever solution O(n log n)
based on:
http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence#Faster_Algorithm
"""
n = len(nums)
if n == 0:
return 0
# Add the first index to the list
# a[i] is the index of the smallest final value
# for an increasing subsequence with length i
a = [0]
# Loop through all the other elemts
for i in xrange(n):
if (nums[a[-1]] < nums[i]):
a.append(i)
continue
# Binary search to find which subsequent length this will be
u = 0
v = len(a)-1
while u < v:
c = (u + v) // 2
if (nums[a[c]] < nums[i]):
u = c + 1
else:
v = c
# Replace the element in the helper list if smaller than we
# had already
if (nums[i] < nums[a[u]]):
a[u] = i
return len(a)
def main(argv=None):
if (argv==None):
argv = sys.argv
# Load information from file
filename = argv[1]
f = open(filename, 'r')
nums = []
for line in f.readlines():
nums.append(int(line))
# # Dynamic programming
# print findlongest(nums)
# Test+Search
print findlongest2(nums)
if __name__ == "__main__":
main()
|
f3032a78f96bd74011401e625d5f20c263cad637 | TheGavinCorkery/BattleshipPythonGame | /Player.py | 1,570 | 3.828125 | 4 | from Board import Board
class Player():
def __init__(self):
self.my_board = Board()
self.guess_board = Board()
self.opponent_board = []
self.hits = 0
#Control all methods to guess a spot on opponents board
def guess_spot(self):
print('Here is your current guessing board')
self.print_guess_board()
guess_space = self.get_guess_space()
#Update guess board with a hit or a miss
hit_or_miss = self.space_hit_or_miss(guess_space)
self.update_guess_board(guess_space, hit_or_miss)
def print_guess_board(self):
for row in self.guess_board.player_board:
print(' '.join(row))
def space_hit_or_miss(self,guess_space):
if self.opponent_board.player_board[guess_space[1]][guess_space[0]] == 'x':
print ("Congrats, you sunk my battleship")
self.hits += 1
return True
else:
print('You missed!')
return False
#Method to get input from user on their space to guess and returns it as a list
def get_guess_space(self):
guess_row = int(input('What row do you want to guess?: '))
guess_col = int(input('What column do you want to guess?: '))
return [guess_row, guess_col]
def update_guess_board(self, guessed_space, did_it_hit):
if did_it_hit == True:
self.guess_board.player_board[guessed_space[1]][guessed_space[0]] = 'H'
else:
self.guess_board.player_board[guessed_space[1]][guessed_space[0]] = 'M'
|
6dd2950189bb6d780432ea24b884b5a01b6406cd | Joghur/modbus-reader | /data/queries.py | 1,820 | 3.625 | 4 | import sys
from utils.files import import_config
"""Methods for manipulating a SQlite database
Create and insert methods
SQL queries are defined at top of file
"""
# getting database configurations
config = import_config('config_database.json')
# guard clause in case config file doesn't exist
if not config:
sys.exit(2)
# defining SQL queries
# create_table_query = f'''
# CREATE TABLE {config['TABLE_NAME']} (
# {config['DATE_COLUMN_NAME']} timestamp NOT NULL PRIMARY KEY,
# {config['SECRET_STRING_COLUMN_NAME']} text NOT NULL
# );
# '''
# # parameterized query to avoid SQL injection
# insert_data_query = f'''
# INSERT INTO {config['TABLE_NAME']}
# (
# {config['DATE_COLUMN_NAME']},
# {config['SECRET_STRING_COLUMN_NAME']}
# )
# VALUES (?, ?)
# ;
# '''
def create_table_query():
return f'''
CREATE TABLE {config['TABLE_NAME']} (
{config['DATE_COLUMN_NAME']} timestamp NOT NULL PRIMARY KEY,
{config['SECRET_STRING_COLUMN_NAME']} text NOT NULL
);
'''
def insert_data_query():
# parameterized query to avoid SQL injection
return f'''
INSERT INTO {config['TABLE_NAME']}
(
{config['DATE_COLUMN_NAME']},
{config['SECRET_STRING_COLUMN_NAME']}
)
VALUES (?, ?)
;
''' |
6cd9cc1bb0048fc3414916d3da5652c816258ba6 | noah-daniel-mancino/algorithms-on-the-side | /max_line.py | 804 | 3.546875 | 4 | """
You can characterize each line by the m and b in y = mx + b. Do this for each
pair of lines, and see which ones pops up the most.
"""
def max_points(points):
lines = set()
lines_frequency = {}
for index, point in enumerate(points):
other_points = points[index + 1:]
print(other_points)
for other_point in other_points:
slope = (point[1] - other_point[1])/(point[0] - other_point[0])
y_intercept = point[1] - (slope * point[0])
if (slope, y_intercept) in lines:
lines_frequency[(slope, y_intercept)] += 1
else:
lines_frequency[(slope, y_intercept)] = 1
lines.add((slope, y_intercept))
return max(lines_frequency.values())
print(max_points([[1,1],[2,2],[3,3],[7,2]]))
|
198648ec4ed8b8019cbb6ce31ec4e561429f9600 | TheSliceOfPi/Practice-Questions | /sumSquareDiff.py | 551 | 4 | 4 | '''
The sum of the squares of the first ten natural numbers is,
The square of the sum of the first ten natural numbers is,
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is .
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
'''
def sumSqrDiff(num):
add=0
sqr=0
for i in range(1,num+1):
add+=i**2
sqr+=i
sqr=sqr**2
diff=sqr-add
return diff
num=100
print(sumSqrDiff(num)) |
3ef4d753b1429f9cdb1ea4ed7a02fbe80387a3ac | Scarlett4431/LeetCode | /150.py | 901 | 3.515625 | 4 | #150. Evaluate Reverse Polish Notation
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack= []
for t in tokens:
if t!='+' and t!='-' and t!='*' and t!='/':
stack.append(t)
else:
b = int(stack.pop())
a = int(stack.pop())
if t=='+':
r= a+b
stack.append(r)
if t=='-':
r= a-b
stack.append(r)
if t=='*':
r= a*b
stack.append(r)
if t=='/':
if a*b <0:
r= -(abs(a)//abs(b))
else:
r= a//b
stack.append(r)
q= stack.pop()
return q |
27ea6e6eec457d29ee6f9cc7d147043649c9f5e8 | shami09/IvLabs | /conditionex3.1.py | 206 | 3.859375 | 4 | hrs = input("Enter Hours:")
h = float(hrs)
rate=input("Enter Rate:")
r=float(rate)
if h > 40:
nom=h*r
ep=(h-40)*(r*0.5)
pay=nom+ep
else:
pay=h*r
print("Pay:",pay) |
231f69494ca4939e8d1d698aa49559a526f7cc8a | DHSZ/igcse-pre-release-summer-2021-22 | /task2.py | 6,778 | 4.21875 | 4 | """
Summer 2021 - Pre-release material
Python project to manage a electric mountain railway system
Author: Jared Rigby (JR)
Most recent update: 19/03/2021
"""
# Task 1 - Start of the day
train_times_up = [900, 1100, 1300, 1500] # Train times for going up the mountain
train_seats_up = [480, 480, 480, 480] # Number of seats available up the mountain
money_up = [0, 0, 0, 0] # The amount of money made by each train up the mountain
train_times_down = [1000, 1200, 1400, 1600] # Train times for going up the mountain
train_seats_down = [480, 480, 480, 640] # Number of seats available up the mountain
money_down = [0, 0, 0, 0] # The amount of money made by each train up the mountain
RETURN_TICKET = 50 # CONSTANT - the price of a return ticket
JOURNEYS_EACH_DAY = len(train_times_up) # CONSTANT - the number of return journeys each day
# Reusable procedure which lists all train times and the seats available
def display_board():
print("\n------------ Trains uphill ------------")
for x in range(len(train_times_up)):
print("Time:", train_times_up[x], "\tSeats:", train_seats_up[x])
print("----------- Trains downhill -----------")
for x in range(len(train_times_down)):
print("Time:", train_times_down[x], "\tSeats:", train_seats_down[x])
display_board() # Use the display_board() procedure to list all train times and seats for the day
# Task 2 - Purchasing tickets
customer_type = 0 # Stores the type of customer booking (single or group)
tickets_needed = 0 # Stores the user input for the number of tickets needed
free_tickets = 0 # Stores how many free tickets the user will receive
total_price = 0 # Stores the total price of the transaction
departure_time = 0 # Will store user input for time up the mountain
return_time = 0 # Will store user input for time down the mountain
departure_index = -1 # Stores the array element for the train up the mountain
return_index = -1 # Stores the array element for the train down the mountain
enough_seats_up = False # Flag variable for available seats
enough_seats_down = False # Flag variable for available seats
# Shopping loop - will run until the end of the day calculation is requested
while customer_type != 3:
customer_type = 0 # Reset customer_type for each transaction
enough_seats_up = False # Reset flags for each transaction
enough_seats_down = False # Reset flags for each transaction
print("\nPlease make a selection")
print("--------------------------")
print("1 - Single customer booking")
print("2 - Group customer booking")
print("3 - To close the ticket booth and output today's totals\n")
while customer_type != 1 and customer_type != 2 and customer_type != 3:
customer_type = int(input("Please enter 1, 2 or 3: "))
# Validation loop - will only exit when the customer selects a possible number of tickets
while enough_seats_up is False or enough_seats_down is False:
# Reset all validation variables
tickets_needed = 0
departure_index = -1
return_index = -1
if customer_type == 1:
print("Single customer booking")
tickets_needed = 1 # Single bookings only need 1 ticket
elif customer_type == 2:
# Input and validation for the number of tickets needed for a group booking
print("Group customer booking")
while tickets_needed < 2:
tickets_needed = int(input("Please enter the number of tickets required... "))
else:
print("Calculating today's totals")
break
# Input and validation of the train times
while departure_index == -1 or return_index == -1:
# Ask the user to enter train times
departure_time = int(input("Please enter the departure time... "))
return_time = int(input("Please enter the return time... "))
# Check if the journey up the mountain exists
for x in range(JOURNEYS_EACH_DAY):
if departure_time == train_times_up[x]:
print("Train at", departure_time, "found!")
departure_index = x
if departure_index == -1:
print("No train found at", departure_time)
# Check if the journey down the mountain exists
for y in range(JOURNEYS_EACH_DAY):
if return_time == train_times_down[y]:
print("Train at", return_time, "found!")
return_index = y
if return_index == -1:
print("No train found at", return_time)
# Check the logical order of the journeys (up happens before down)
if departure_time > return_time:
return_index = -1
departure_index = -1
print("Error - you can't depart after you return")
# Check enough seats are available
if train_seats_up[departure_index] - tickets_needed < 0:
print("Error - not enough seats available up the mountain")
else:
enough_seats_up = True
if train_seats_down[return_index] - tickets_needed < 0:
print("Error - not enough seats available down the mountain")
else:
enough_seats_down = True
# Calculate the price
if tickets_needed < 10:
total_price = tickets_needed * RETURN_TICKET
elif tickets_needed >= 10:
free_tickets = tickets_needed // 10
if free_tickets > 8: # Set an upper limit for free tickets
free_tickets = 8
total_price = (tickets_needed * RETURN_TICKET) - (free_tickets * RETURN_TICKET)
# Do not show the invoice for customer type 3
if customer_type != 3:
print("\n------ CUSTOMER INVOICE ------")
print("Tickets:", tickets_needed)
print("Total price:", total_price)
print("Free tickets:", free_tickets)
print("------------------------------\n")
# Update the data for the display board
train_seats_up[departure_index] = train_seats_up[departure_index] - tickets_needed
train_seats_down[return_index] = train_seats_down[return_index] - tickets_needed
# Update the arrays which store the amount of money received by each train service
money_up[departure_index] = money_up[departure_index] + (total_price / 2)
money_down[return_index] = money_down[return_index] + (total_price / 2)
# Output the display board with the latest values
display_board()
print("Task 3 will happen here!") |
f4a47627b293951f8f6c408628b7034809e5c68a | emildoychinov/Talus | /loader/cogs/ttt.py | 6,769 | 3.671875 | 4 | from discord.ext import commands
import time
#a util function that will be used to make a list into a string
makeStr = lambda list : ''.join(list)
class tictactoe(commands.Cog):
def __init__(self, bot, comp_sign='x', p_sign='o'):
self.bot = bot
self.pos=0
self.p_move = -1
self.comp_move = 1
self.comp_sign = comp_sign
self.p_sign = p_sign
self.field = ['-']*9
#a function to represent the board and to make it ready for printing
def represent(self, flag=0):
fld = list(self.field)
for i in range (0,9):
if flag==0:
fld[i]+=' '
if i%3 == 0 and flag==0:
fld[i-1]+='\n'
return makeStr(fld)
#here we check if the game has been won
def win (self, fld=None):
if fld is None : fld = list(self.represent(1))
#the positions for winning
winPos = [[0,1,2], [0,3,6], [0,4,8], [1,4,7], [2,4,6], [2,5,8], [3,4,5], [6,7,8]]
#check
for i in range(8):
# if the player wins we return -1 and if the bot wins we return 1, that will be used in the algorithm for the bot
if fld[winPos[i][0]] == fld[winPos[i][1]] and fld[winPos[i][0]] == fld[winPos[i][2]] and fld[winPos[i][0]]!='-':
return -1 if fld[winPos[i][0]] == self.p_sign else 1
#if it is a draw or the game has not yet ended we return 0
return 0
#a utility function to edit a discord message
async def edt (self, ctx, cnt, msg, auth_msg = None):
if auth_msg is not None :
await auth_msg.delete()
await msg.edit(content = cnt)
return msg
#the bot algorithm
def minimax(self, pl, fld = None):
if fld is None:
fld = list(self.represent(1))
#if the game has ended we return either -1 or 1, depending on who won
end = self.win(fld)
if end : return end*pl
#we start from negative score : we prefer a move that could lead to a draw rather than a move that could lead to the opposing player winning
score = -10
move=-10
for i in range(9):
#we check if the position is available
if fld[i] == '-':
#test the position
fld[i] = self.p_sign if pl==-1 else self.comp_sign
#see how the position will look like for the opposing player
moveScore = -self.minimax(-pl, fld)
if moveScore > score :
score = moveScore
move = i
#we return the field on the given position back to normal
fld[i] = '-'
#if no move has been made we return 0
if move == -10 :
return 0
#if there has been a move made but no one has yet won we return the score
return score
#here we make a move based on the results from the minimax function (a full tree search of the tictactoe board)
def makeMove(self):
fld = list(self.represent(1))
score = -10
for i in range(9):
#if available
if fld[i] == '-':
#test the move
fld[i] = self.comp_sign
#see how it will look like for the opposing player
thisScore = -self.minimax(-self.comp_move, fld)
fld[i] = '-'
#if the score of the move is better than the current score we save it
if thisScore>score :
score = thisScore
move = i
#we return the move+1
return move+1
#a utility function for deleting a certain message
async def delTrace (self, ctx, msg):
await msg.delete()
@commands.command()
#here the game is played off
async def game(self, ctx):
self.field = ['-']*9
msg = await ctx.channel.send('```WELCOME TO THE GAME OF TICTACTOE!\n Do you want to be (f)irst or (s)econd?\n```')
#we wait to see if the player wants to be first or second
a = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
if (a.content == 'f'):
flg = 0
self.p_sign = 'x'
self.comp_sign = 'o'
else :
flg = 1
self.p_sign = 'o'
self.comp_sign = 'x'
for i in range(9):
#if the game has been won
if self.win():
#edit the board
msg = await self.edt(ctx, '```THE GAME HAS ENDED! '+('I WIN!\n' if self.win()==1 else 'YOU WIN!\n')+self.represent()+'\n```', msg)
time.sleep(1.5)
#delete the board
await self.delTrace(ctx, msg)
return
try :
#a is an argument that is None by default, it's the player's message : if it doesn't exist we catch the exception and proceed without it
#if it does, we delete it
msg = await self.edt(ctx, '```\n'+self.represent()+'\n```', msg, a)
except :
msg = await self.edt(ctx, '```\n'+self.represent()+'\n```', msg)
#flg is the flag for the player : if he is first it's 0, otherwise it's 1
if i%2 == flg:
#we wait for the player's move
a = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
#a cheeky easter egg :)
if a.content == 'stop' :
await ctx.channel.send('```\nOkay, I get it, human. You are too weak\n```')
return
#we check if the move is valid
#if it is not, it becomes 0
pos = (int(a.content) if a.content.isdigit() else 0) if i%2==flg else self.makeMove()
#while the move is invalid
while pos > 9 or pos<=0 or self.field[pos-1]!='-':
#we wait for a new one
a = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
pos = int(a.content)
#we make the move
self.field[pos-1] = self.p_sign if i%2 == flg else self.comp_sign
try :
msg = await self.edt(ctx, '```THE GAME HAS ENDED! IT IS A DRAW!\n'+self.represent()+'\n```', msg, a)
except :
msg = await self.edt(ctx, '```THE GAME HAS ENDED! IT IS A DRAW!\n'+self.represent()+'\n```', msg)
time.sleep(1.5)
await self.delTrace(ctx, msg)
#setting up the cog for the bot...
def setup(bot):
bot.add_cog(tictactoe(bot))
|
fb04a8d334283582cca10c9ae04126e97476f4f9 | wchi619/Python-Assignment-1 | /a1_wchi3.py | 6,844 | 4.53125 | 5 | #!/usr/bin/env python3
"""
OPS435 Assignment 1 - Fall 2019
Program: a1_wchi3.py
Author: William Chi
This program will return the date in YYYY/MM/DD after the given day (second argument) is passed. This program requires 2 arguments with an optional --step flag.
"""
# Import package
import sys
def usage():
"""Begin usage check. """
if len(sys.argv) != 3 or len(sys.argv[1]) != 10 or sys.argv[2].lstrip("-").isdigit() == False: #Argument parameter check
print("Error: wrong date entered")
exit()
else: #If error check pass, continue program and return date and days
date = str(sys.argv[1])
days = int(sys.argv[2])
return date, days
def valid_date(date):
"""Validate the date the user inputs.
This function will take a date in "YYYY/MM/DD" format, and return True if the given date is a valid date, otherwise return False plus an appropriate status message. This function will also call another function to double check that the days in month entered is correct.
"""
days_in_mon(date)
# Begin date validation
if int(date[0:4]) not in range(1, 2050):
print("Error: wrong year entered")
exit()
elif int(date[5:7]) not in range(1, 13):
print("Error: wrong month entered")
exit()
elif int(date[8:10]) not in range(1, 32):
print("Error: wrong day entered")
exit()
elif leap_year(date) == False and date[5:7] == '02' and int(date[8:10]) in range(29,32): # If not leap year but date entered is Feb 29-31
print("Error: Invalid day entered (not a leap year).")
exit()
elif leap_year(date) == True and date[5:7] == '02' and int(date[8:10]) not in range(1,30): # If leap year, but date entered is Feb 30-31
print("Error: Invalid day entered (01-29 only).")
exit()
else:
return True
def days_in_mon(date):
"""Creates dictionary of the maximum number of days per month.
This function will take a year in "YYYY" format and return a dictionary object which contains the total number of days in each month for the given year. The function will also call another function to check for leap year.
"""
leap_year(date)
days_per_month = {
'1' : 31,
'2' : 28,
'3' : 31,
'4' : 30,
'5' : 31,
'6' : 30,
'7' : 31,
'8' : 31,
'9' : 30,
'10' : 31,
'11' : 30,
'12' : 31,
}
if leap_year(date) == True:
days_per_month['2'] = 29 # Change Feb to 29 if leap year
return days_per_month
else:
return days_per_month
def leap_year(date):
"""Double check if the year entered is a leap year or not.
This function will take a year in "YYYY" format and return True if the year is a leap year, otherwise return False.
"""
year = int(date[0:4]) # Grab year
# Leap year test will only return True on 2 conditions:
# 1. The century year is divisible by 400, OR
# 2. The year is divisible by 4 AND IS NOT divisible by 100 (omit century years).
if ((year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0))):
return True
else:
return False
def after(date, days):
"""Returns the final calculated value of the date.
This function will take a date and a positive integer, add the integer as the amount of days to the date and return the final date. This function will also call on another function to retrieve a dictionary of the total number of days per each month (also accounting for leap years).
"""
dictionary = days_in_mon(date)
year, month, day = date.split('/')
year = int(year)
month = int(month)
day = int(day)
# Define variables for the final month & day.
nmonth = month
nday = day
for i in range(days):
# Resets day to 1 if it exceeds the total days in a month.
if nday >= dictionary[str(month)]:
month = month + 1
nday = 1
nmonth = nmonth + 1
else:
nday = nday + 1
# Resets month to 1 if it exceeds the total months in a year.
if nmonth > 12:
nmonth = 1
month = 1
year = year + 1
n = str(year) + "/" + str(nmonth).zfill(2) + "/" + str(nday).zfill(2)
return n
def before(date, days):
"""Returns the final calculated value of the date.
This function will take a date and a negative integer, subtract the date with the amount of days and return the final date. This function will also call on another function to retrieve a dictionary of the total number of days per each month (also accounting for leap years).
"""
dictionary = days_in_mon(date)
year, month, day = date.split('/')
year = int(year)
month = int(month)
day = int(day)
# Define variables for the final month & day.
nmonth = month
nday = day
for i in range(days, 0):
if nday <= 1:
month = month - 1
if month == 0:
month = 1
# Set the month to the highest value allowed in that month.
nday = dictionary[str(month)]
nmonth = nmonth - 1
else:
nday = nday - 1
# Reset month to 12 if it is lower than the total months in a year.
if nmonth < 1:
nmonth = 12
month = 12
year = year - 1
n = str(year) + "/" + str(nmonth).zfill(2) + "/" + str(nday).zfill(2)
return n
def dbda(date, days):
"""Calls the correct function to calculate the date.
This function will retrieve the validated date and days and depending on the value of the integer it will call 2 separate functions.
"""
if int(sys.argv[2]) >= 0:
return after(date, days)
else:
before(date, days)
return before(date, days)
if __name__ == "__main__":
# Executed first: figure out if --step option is present or not, and pop itif necessary.
if sys.argv[1] == '--step':
step = True
sys.argv.pop(1)
usage()
else:
step = False
usage()
# Argument initialization
date = str(sys.argv[1])
days = int(sys.argv[2])
valid_date(date) # Begin date validation.
# Call calculation function to print the final date.
if step == True:
if days > 0: # Loop to print positive date step by step.
for i in range(1, days+1):
final_date = dbda(date, i)
print(final_date)
else: # Loop to print negative date step by step (reverse order).
for i in reversed(range(days, 0)):
final_date = dbda(date, i)
print(final_date)
if step == False: # Loop to print normally if no --step option inputted.
final_date = dbda(date,days)
print(final_date)
|
4deb99f3c3c58525f632d85d77c748be62a7ce5b | juraj80/Python-Data-Stuctures | /10/romeo.py | 430 | 3.8125 | 4 | ''' print the ten most common words in the text '''
import string
handle=open('romeo-full.txt')
counts=dict()
for line in handle:
line=line.translate(None,string.punctuation)
line=line.lower()
words=line.split()
for word in words:
if not word in counts:
counts[word]=1
else:
counts[word]=counts[word]+1
res=list()
for k,v in counts.items():
res.append((v,k))
res.sort(reverse=True)
for k,v in res[:10]:
print v,k
|
cf8efc269f8d53acd9b41e2bc876a32f3b11c620 | juraj80/Python-Data-Stuctures | /09/bigcountA.py | 596 | 3.53125 | 4 | name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
emails=list()
for line in handle:
line=line.rstrip()
if line=="":continue
if not line.startswith("From:"):continue
words=line.split()
emails.append(words[1])
counts=dict()
for email in emails:
if not email in counts:
counts[email]=1
else:
counts[email]=counts[email]+1
print counts
bigcount=None
bigemail=None
for email,count in counts.items():
if bigcount is None or count>bigcount:
bigcount=count
bigemail=email
print bigemail,bigcount
|
4bd83144bd8246dd40fd063efb8ccb6808ab4abf | juraj80/Python-Data-Stuctures | /07/enterfile.py | 171 | 3.59375 | 4 | inp=raw_input("Enter a file:")
try:
file=open(inp)
except:
print "Error. Please Enter a File."
exit()
for line in file:
line=line.rstrip()
print line
|
f81888b47c87ceefa5f458913dbcc47319dfc185 | chavadasagar/python | /fectorial.py | 204 | 3.875 | 4 | n = int(input("enter number"))
fec = 1
for x in range(1,n+1):
fec = fec * x
print(fec)
'''
# using recursion
def fec(n):
if n == 1:
return 1
else:
return n * fec(n-1)
'''
|
a1d76dd2a74db5557596f2f3da1fbb2bf70474d2 | chavadasagar/python | /reverse_string.py | 204 | 4.40625 | 4 | def reverse_str(string):
reverse_string = ""
for x in string:
reverse_string = x + reverse_string;
return reverse_string
string = input("Enter String :")
print(reverse_str(string))
|
6992e8064e8031e1b0023071471f937152b69263 | Dakarai/war-card-game | /main.py | 3,338 | 3.53125 | 4 | import random
suits = ('Clubs', 'Diamonds', 'Hearts', 'Spades')
ranks = ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')
values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
war_cards_count = 3
class Card:
def __init__(self, suit, rank):
self.suit = suit[0].lower()
self.rank = rank
self.value = values[rank]
def __repr__(self):
return self.rank + "" + self.suit
class Deck:
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
self.all_cards.append(Card(suit, rank))
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop(0)
class Player:
def __init__(self, name):
self.name = name.capitalize()
self.all_cards = []
def remove_one(self):
return self.all_cards.pop(0)
def add_cards(self, new_cards):
if type(new_cards) == type([]):
self.all_cards.extend(new_cards)
else:
self.all_cards.append(new_cards)
def __str__(self):
return f"Player {self.name} has {len(self.all_cards)} cards."
if __name__ == '__main__':
# create players
player_one = Player("One")
player_two = Player("Two")
# create deck object and shuffle it
new_deck = Deck()
new_deck.shuffle()
# split shuffled deck between players
for x in range(26):
player_one.add_cards(new_deck.deal_one())
player_two.add_cards(new_deck.deal_one())
play_game = True
round_number = 0
while play_game:
round_number += 1
print(f"Round {round_number}")
if len(player_one.all_cards) == 0:
print('Player One has lost!')
play_game = False
break
elif len(player_two.all_cards) == 0:
print('Player Two has lost!')
play_game = False
break
# start a new round
player_one_cards = [player_one.remove_one()]
player_two_cards = [player_two.remove_one()]
end_of_round = False
while not end_of_round:
# evaluate round
if player_one_cards[-1].value > player_two_cards[-1].value:
player_one.add_cards(player_one_cards)
player_one.add_cards(player_two_cards)
end_of_round = True
print(player_one_cards)
print(player_two_cards)
print(player_one)
print(player_two)
break
elif player_one_cards[-1].value < player_two_cards[-1].value:
player_two.add_cards(player_two_cards)
player_two.add_cards(player_one_cards)
end_of_round = True
print(player_one_cards)
print(player_two_cards)
print(player_one)
print(player_two)
break
else:
for _ in range(war_cards_count):
if len(player_one.all_cards) > 0:
player_one_cards.append(player_one.remove_one())
if len(player_two.all_cards) > 0:
player_two_cards.append(player_two.remove_one())
|
4ca802795b88b9a184cb4fedd62ad242a5ba59e4 | theballkyo/GetA | /classes/gradebar.py | 1,594 | 3.53125 | 4 | from tkinter import *
class Progressbar():
obj_progress = False
def __init__(self, root, max_width, max_height, score):
bar = Label(root)
bar.place(x=60,y=30)
self.canvas = Canvas(bar, width=max_width-2, height=max_height)
self.canvas.pack()
self.color = self.get_color(score)
self.canvas_rec = self.canvas.create_rectangle(2, 2, max_width, max_height, fill=self.color, outline="black")
self.max_width = max_width
self.max_height = max_height
def get_color(self, total_score):
if total_score == 0:
color = "light grey"
elif total_score >= 80:
color = "green"
elif total_score >= 75:
color = "green yellow"
elif total_score >= 70:
color = "yellow"
elif total_score >= 65:
color = "gold"
elif total_score >= 60:
color = "dark orange"
elif total_score >= 55:
color = "red"
elif total_score >= 50:
color = "brown"
elif total_score < 50:
color = "dark red"
return color
def update(self, progress):
self.canvas.itemconfig(self.canvas_rec, fill=self.get_color(progress))
self.progress = min(max(progress, 0), 100)
self.canvas.delete(self.obj_progress)
pixel_height = self.max_height - ((self.progress * self.max_height))/100.0
if self.progress >= 0:
self.obj_progress = self.canvas.create_rectangle(3, 3, self.max_width, pixel_height, fill='lightgrey', outline='black')
|
86643c2fe7599d5b77bdcbe3e6c35aa88ba98ecc | aemperor/python_scripts | /GuessingGame.py | 2,703 | 4.25 | 4 | ## File: GuessingGame.py
# Description: This is a game that guesses a number between 1 and 100 that the user is thinking within in 7 tries or less.
# Developer Name: Alexis Emperador
# Date Created: 11/10/10
# Date Last Modified: 11/11/10
###################################
def main():
#A series of print statements to let the user know the instructions of the game.
print "Guessing Game"
print ""
print "Directions:"
print "Think of a number between 1 and 100 inclusive."
print "And I will guess what it is in 7 tries or less."
print ""
answer = raw_input ("Are you ready? (y/n): ")
#If the user inputs that "n", no, he is not ready, prompt him over and over
while (answer != "y"):
answer = raw_input ("Are you ready? (y/n): ")
#If the user inputs yes, start the program
if (answer == "y"):
count = 1
hi = 100
lo = 1
mid = (hi+lo)/2
print "Guess",count,": The number you thought was:",mid
correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
while (correct != "0"):
#Iterate a loop that resets when correct isn't equal to zero
while (count < 7):
#Iterate a loop that stops the program when count gets to 7
if (correct == "0"):
print "I win! Thank you for playing the Guessing Game."
break
#If correct == 0 then the program wins
if (correct == "1"):
#If correct == 1 then reset the values of hi and lo to take a new average
hi = mid
lo = lo + 1
mid = (hi+lo)/2
count = count + 1
print "Guess",count, ": The number you thought was:",mid
correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
if (correct == "-1"):
#If correct == -1 then reset the values of hi and lo to take a new average
hi = hi + 1
lo = mid - 1
mid = (hi+lo)/2
count = count + 1
print "Guess",count, ": The number you thought was:",mid
correct = raw_input ("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
if (count >= 7):
#If count exceeds 7 then the user is not thinking of a number between 1 and 100.
print "The number you are thinking of is not between 1 and 100."
break
main()
|
4978f92dab090fbf4862c4b6eca6db01150cf0b7 | aemperor/python_scripts | /CalcSqrt.py | 1,059 | 4.1875 | 4 | # File: CalcSqrt.py
# Description: This program calculates the square root of a number n and returns the square root and the difference.
# Developer Name: Alexis Emperador
# Date Created: 9/29/10
# Date Last Modified: 9/30/10
##################################
def main():
#Prompts user for a + number
n = input ("Enter a positive number: ")
#Checks if the number is positive and if not reprompts the user
while ( n < 0 ):
print ("That's not a positive number, please try again.")
n = input ("Enter a positive number: ")
#Calculates the initial guesses
oldGuess = n / 2.0
newGuess = ((n / oldGuess) + oldGuess) / 2.0
#Loops the algorithm until the guess is below the threshold
while ( abs( oldGuess - newGuess ) > 1.0E-6 ):
oldGuess = newGuess
newGuess = ((n / oldGuess) + oldGuess) / 2.0
#Calculates the difference between the actual square and guessed
diff = newGuess - (n ** .5)
#Prints the results
print 'Square root is: ', newGuess
print 'Difference is: ', diff
main()
|
a7eda8fb8d385472dc0be76be4a5397e7473f724 | petyakostova/Software-University | /Programming Basics with Python/First_Steps_in_Coding/06_Square_of_Stars.py | 237 | 4.15625 | 4 | '''Write a console program that reads a positive N integer from the console
and prints a console square of N asterisks.'''
n = int(input())
print('*' * n)
for i in range(0, n - 2):
print('*' + ' ' * (n - 2) + '*')
print('*' * n)
|
62e95db13611d9a6ecbdbb070b9b176d673b81f2 | petyakostova/Software-University | /Programming Basics with Python/First_Steps_in_Coding/04_Triangle_Of_55_Stars.py | 300 | 3.984375 | 4 | '''
Write a Python console program that prints a triangle of 55 asterisks located in 10 rows:
*
**
***
****
*****
******
*******
********
*********
**********
'''
for i in range(1,11):
print('*'*i)
'''
for i in range(1, 11):
for j in range(0, i):
print('*', end="")
print()
''' |
3f25e4489c087b731396677d6337e4ad8633e793 | petyakostova/Software-University | /Programming Basics with Python/Simple-Calculations/08-Triangle-Area.py | 317 | 4.3125 | 4 | '''
Write a program that reads from the console side and triangle height
and calculates its face.
Use the face to triangle formula: area = a * h / 2.
Round the result to 2 decimal places using
float("{0:.2f}".format (area))
'''
a = float(input())
h = float(input())
area = a * h / 2;
print("{0:.2f}".format(area))
|
b8e9d1e43fb13bbe5056d92687169e83393add1a | Isaac51743/Algorithms-in-Python | /src/recursion/recursion1.py | 739 | 4.0625 | 4 | # 12/18/2020
def fibonacci(index):
if index == 0 or index == 1:
return index
return fibonacci(index - 1) + fibonacci(index - 2)
print(fibonacci(4))
# assuming a and b are both integer, return type is double
def a_power_b(a, b):
if a == 0 and b <= 0:
return None
elif a == 0 and b > 0:
return 0
elif a != 0 and b < 0:
return 1 / a_power_b(a, -b)
else:
# base case
if b == 0:
return 1
elif b == 1:
return a
# recursive rules
square_root = a_power_b(a, b // 2)
if b % 2 == 1:
return square_root * square_root * a
else:
return square_root * square_root
print(a_power_b(-2, -4)) |
09ff50c23a5e27d558ed1c7769439bf28b0243e3 | Isaac51743/Algorithms-in-Python | /src/bits_probability_dfs/probability.py | 2,830 | 3.609375 | 4 | import random as r
import heapq as hq
def shuffle_poker(array):
if len(array) != 52:
return
for idx in range(52):
random_idx = r.randint(idx, 51)
array[idx], array[random_idx] = array[random_idx], array[idx]
test_array = [i for i in range(52)]
shuffle_poker(test_array)
print(test_array)
def get_random_in_flow(input, time):
if r.randint(0, time) == 0:
global random_element
random_element = input
def get_randomk_in_flow(input, time, k, random_k):
if time < k:
random_k.append(input)
else:
random_idx = r.randint(0, time)
if random_idx < k:
random_k[random_idx] = input
test_flow1 = [1, 3, 9, 5, 2, 7, 12, 21, 8, 6]
random_element = None
for index, value in enumerate(test_flow1):
get_random_in_flow(value, index)
print(random_element, end=' ')
print()
k = 3
random_k = []
for index in range(len(test_flow1)):
get_randomk_in_flow(test_flow1[index], index, k, random_k)
print(random_k, end=' ')
print()
def random_largest(input, time):
global largest,counter, largest_idx
if input == largest:
counter += 1
if r.randint(1, counter) == 1:
largest_idx = time
elif input > largest:
largest = input
counter = 1
largest_idx = time
largest_idx = -1
counter = 0
largest = float("-inf")
test_flow2 = [1, 3, 9, 5, 2, 3, 9, 2, 9, 2]
for index, value in enumerate(test_flow2):
random_largest(value, index)
print(largest_idx, end=' ')
print()
def random_5():
result = r.randint(0, 6)
while result >= 5:
result = r.randint(0, 6)
return result
def random_7():
result = 0
for i in range(2):
result = result * 5 + r.randint(0, 4)
while result >= (25 // 7 * 7):
result = 0
for i in range(2):
result = result * 5 + r.randint(0, 4)
return result % 7
for i in range(10):
print(random_5(), end=' ')
print("random 5 based on random 7")
for i in range(10):
print(random_7(), end=' ')
print("random 7 based on random 5")
def get_median(input, small_heap, big_heap):
if len(small_heap) == len(big_heap):
if not small_heap or input <= big_heap[0]:
hq.heappush(small_heap, -input)
else:
hq.heappush(small_heap, -1 * hq.heappop(big_heap))
hq.heappush(big_heap, input)
else:
if input >= -1 * small_heap[0]:
hq.heappush(big_heap, input)
else:
hq.heappush(big_heap, -1 * hq.heappop(small_heap))
hq.heappush(small_heap, -input)
if len(small_heap) == len(big_heap):
return (big_heap[0] - small_heap[0]) / 2
return -1 * small_heap[0]
s_heap = []
b_heap = []
for element in test_flow2:
print(get_median(element, s_heap, b_heap), end=' ')
print() |
21e2669bf38725d1cd712ed2b7ffd2c01dfb5ed4 | Isaac51743/Algorithms-in-Python | /src/code_review3.py | 2,409 | 3.59375 | 4 | import math
def dropped_request(time_list):
if len(time_list) == 0:
return 0
dropped_num = 0
for index in range(len(time_list)):
case1 = index >= 3 and time_list[index] - time_list[index - 3] + 1 <= 1
case2 = index >= 20 and time_list[index] - time_list[index - 20] + 1 <= 10
case3 = index >= 60 and time_list[index] - time_list[index - 60] + 1 <= 60
if case1 or case2 or case3:
dropped_num += 1
return dropped_num
time_spots = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 11, 11, 11, 11]
print(dropped_request(time_spots))
# Given a positive integer n, how many ways can we write it as a sum of consecutive positive integers?
def consecutive_numbers_sum(n):
num_of_seq = 0
for sequence_size in range(2, int(0.5 + 0.5 * math.sqrt(1 + 8 * n))):
temp = n - (sequence_size - 1) * sequence_size // 2
if temp % sequence_size == 0:
num_of_seq += 1
return num_of_seq
print(consecutive_numbers_sum(15))
def find_before_matrix(matrix):
if len(matrix) == 0 or len(matrix[0]) == 0:
return None
before_matrix = [[0] * len(matrix[0]) for _ in range(len(matrix))]
before_matrix[0][0] = matrix[0][0]
for index in range(1, len(matrix[0])):
before_matrix[0][index] = matrix[0][index] - matrix[0][index - 1]
for index in range(1, len(matrix)):
before_matrix[index][0] = matrix[index][0] - matrix[index - 1][0]
for row in range(1, len(matrix)):
for col in range(1, len(matrix[0])):
before_matrix[row][col] = matrix[row][col] - matrix[row - 1][col]\
- matrix[row][col - 1] + matrix[row - 1][col - 1]
return before_matrix
after_matrix = [[1, 2], [3, 4]]
print(find_before_matrix(after_matrix))
# assume all bids greater than 0
def get_0_allotted_user(bids, total_shares):
if len(bids) == 0:
return 0
elif total_shares == 0:
return len(bids)
bids.sort(key=lambda bid: (-1 * bid[2], bid[3]))
for index in range(len(bids)):
if total_shares <= 0:
break
total_shares -= bids[index][1]
user_list = []
while index < len(bids):
user_list.append(bids[index][0])
index += 1
return user_list
bids = [[1, 5, 5, 0], [2, 7, 8, 1], [3, 7, 5, 1], [4, 10, 3, 3]]
print(get_0_allotted_user(bids, 13))
|
b37c28841c34b9a4b44052326d39f4dd7f0c12ae | donaldex/code | /repeat_str.py | 202 | 3.984375 | 4 | def repeat_str():
s = input("Enter string: ")
t = input("Enter int>=0: ")
n = int(t)
print(n*s)
print("anni is stupid")
# return "ddddd"
##repeat_str()
print(repeat_str())
|
15e9c4495517c834dca50c81383cace908117392 | larinanatalia/class | /hw6.py | 1,875 | 3.9375 | 4 | class Animal:
satiety = 'hungry'
def __init__(self, name, weight):
self.name = name
self.weight = weight
def feed(self):
self.satiety = 'animal ate food'
class Bird(Animal):
eggs = 'dont have eggs'
def pick_eggs(self):
self.eggs = 'we picked eggs'
class Goose(Bird):
voice = 'krya-krya'
class Chicken(Bird):
voice = 'kudakh-kudakh'
class Duck(Bird):
voice = 'krya-krya'
class Cow(Animal):
voice = 'muuuu'
milk = 'we need milk'
def get_milk(self):
self.milk = 'milk received'
class Sheep(Animal):
voice = 'beeee'
wool = 'we dont have'
def cut(self):
self.wool = 'we cut the sheep'
class Goat(Animal):
voice = 'meeee'
milk = 'we need milk'
def get_milk(self):
self.milk = 'milk received'
goose_1 = Goose('Gray', 3)
goose_2 = Goose('White', 3.5)
cow = Cow('Manka', 500)
sheep_1 = Sheep('Barashek', 50)
sheep_2 = Sheep('Kudryavyy', 65)
chicken_1 = Chicken('KoKo', 1)
chicken_2 = Chicken('Kukareku', 0.8)
goat_1 = Goat('Roga', 41)
goat_2 = Goat('Kopyta', 45)
duck = Duck('Kryakva', 2)
print(3+3.5+500+50+65+1+0.8+41+45+2)
all_animal = [goose_1, goose_2, cow, sheep_1, sheep_2, chicken_1, chicken_2, goat_1, goat_2, duck]
def print_animal_data(animal_list: list) -> None:
list_animal_weight = list()
sum_animal_weight = 0
list_animal_name = []
for animal in animal_list:
list_animal_weight.append(animal.weight)
for weight in list_animal_weight:
sum_animal_weight += weight
print(sum_animal_weight)
for animal in animal_list:
list_animal_name.append(animal.name)
all_animal_dict = dict(zip(list_animal_name, list_animal_weight))
for key, value in all_animal_dict.items():
if value == max(all_animal_dict.values()):
print(key)
print_animal_data(all_animal)
|
550a70f93c012bb9255ed755c18a74a203ed480f | nkhalili/py-samples | /02/08-conditional-operators.py | 173 | 4 | 4 |
x = 5
y = True
if x == 5 and y:
print('true')
# ternary operator
hungry = 0
result = 'feed the bear now!' if hungry else 'do not feed the bear.'
print(result) |
9790fb0d75f15431ca643b1f65319a329460c902 | nkhalili/py-samples | /02/11-loops-input.py | 320 | 3.796875 | 4 | secret = "secret"
pw = ''
while pw != secret:
if pw == '123': break
pw = input('Enter secret word:')
else: # in case while breaks, else won't run
print('>Secret key is correct.')
animals = ('bear', 'bunny', 'dog', 'cat')
for pet in animals:
print(pet)
else:
print('>Items finished.') |
3197f5ebde279a17087f81362239b07685067bba | nkhalili/py-samples | /02/03-blocks.py | 307 | 3.84375 | 4 | x = 42
y = 73
# Blocks define by indentation e.g. 4 spaces
if x < y:
z = 100
print("x < y: x is {}, y is {}".format(x, y))
## in python blocks do not define scope, Functions, objects, module DO.
# z has the same scope as x and y even though its block is different!
print("z is: ", z)
|
d90948ed064194d3f86571ec3c38f3680a2a9552 | TestardR/Python-algorithms-v1 | /sentence_reversal.py | 507 | 3.9375 | 4 | def rev_word(str):
return " ".join(reversed(str.split()))
def rev_word1(str):
return " ".join(str.split()[::-1])
def rev_word2(str):
words = []
length = len(str)
space = [' ']
i = 0
while i < length:
if str[i] not in space:
word_start = i
while i < length and str[i] not in space:
i += 1
words.append(str[word_start:i])
i += 1
return ' '.join(reversed(words))
print(rev_word2('hello mamacita'))
|
bb2c102167c19e3531e76e3b29da34608283ece8 | MikolajTwarog/Artificial-Intelligence | /connect4/board.py | 3,330 | 3.6875 | 4 | #!/usr/bin/env python3
class Board:
def __init__(self):
self.board = [[0]*7 for i in range(6)]
self.moves = 0
self.end = False
def check_vertical(self, row, column, who):
line = 0
for i in range(row, 6):
if self.board[i][column] == who:
line += 1
else:
break
return line
def check_horizontal(self, row, column, who):
line = 0
for i in range(column, 7):
if self.board[row][i] == who:
line += 1
else:
break
for i in range(column-1, -1, -1):
if self.board[row][i] == who:
line += 1
else:
break
return line
def check_diagonal(self, row, column, who):
line = 1
for i in range(1, min(7 - column, 6 - row)):
if self.board[row+i][column+i] == who:
line += 1
else:
break
for i in range(1, min(column + 1, row + 1)):
if self.board[row-i][column-i] == who:
line += 1
else:
break
line2 = 1
for i in range(1, min(column + 1, 6 - row)):
if self.board[row+i][column-i] == who:
line2 += 1
else:
break
for i in range(1, min(7 - column, row + 1)):
if self.board[row-i][column+i] == who:
line2 += 1
else:
break
return max(line, line2)
def check_draw(self):
for i in range(0, 7):
if self.board[0][i] == 0:
return False
return True
def check_if_end(self, row, column, who):
line = max(self.check_vertical(row, column, who),
self.check_horizontal(row, column, who),
self.check_diagonal(row, column, who))
return line >= 4 or self.check_draw()
def make_move(self, column):
if self.board[0][column] != 0:
return False
who = (self.moves % 2) + 1
row = 5
while self.board[row][column] != 0:
row -= 1
self.board[row][column] = who
self.end = self.check_if_end(row, column, who)
self.moves += 1
return True
def get_children(self):
who = (self.moves % 2) + 1
children = []
for i in range(0, 7):
child = Board()
child.moves = self.moves
child.board = [list(x) for x in self.board]
if child.make_move(i):
children.append((child, i))
return children
def get_possible_moves(self):
moves = []
for i in range(0, 7):
if self.board[0][i] == 0:
moves.append(i)
return moves
def print_board(self):
for i in self.board:
b = ""
for j in i:
if j == 0:
b += '.'
elif j == 1:
b += 'O'
else:
b += 'X'
b += " "
print(b)
print("0 1 2 3 4 5 6")
print()
return
|
87f5fd7703bafe4891fb042de2a7f1770c602995 | BreeAnnaV/CSE | /BreeAnna Virrueta - Guessgame.py | 771 | 4.1875 | 4 | import random
# BreeAnna Virrueta
# 1) Generate Random Number
# 2) Take an input (number) from the user
# 3) Compare input to generated number
# 4) Add "Higher" or "Lower" statements
# 5) Add 5 guesses
number = random.randint(1, 50)
# print(number)
guess = input("What is your guess? ")
# Initializing Variables
answer = random.randint(1, 50)
turns_left = 5
correct_guess = False
# This describes ONE turn (This is the game controller)
while turns_left > 0 and correct_guess is False:
guess = int(input("Guess a number between 1 and 50: "))
if guess == answer:
print("You win!")
correct_guess = True
elif guess > answer:
print("Too high!")
turns_left -= 1
elif guess < answer:
print("Too low!")
turns_left -= 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.