blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
18d67c0ab336dde18bdaa0f1bb308818e78be601 | Allan-Perez/CStudies- | /Algorithms/naive_function.py | 563 | 3.890625 | 4 | # Naive algorithm for multiplying two numbers
# use it with args
import sys
import time
def naive(a,b):
x = a
y = b
z = 0
while y > 0:
z = z + x
y = y - 1
return z
def main(func):
if(len(sys.argv) < 3):
raise Exception("Pass me args to multiply!")
a = int(sys.argv[1])
b = int(sys.argv[2])
init = time.time()
z = func(a,b)
end = time.time()
print("Solution: ", z)
if (end - init) < 1e-3:
print("Running time: %.5g seconds" % (end - init) )
else:
print("Running time: %.5f seconds" % (end - init) )
if __name__ == '__main__':
main(naive) |
600d61cbd3e88dbc7213dba444a67812f358876e | akudaibergen/labsOfwebka | /week8/3h.py | 82 | 3.796875 | 4 | a=int(input("Number is "))
for i in range (1,a+1):
if a%i==0:
print(i) |
56fba54fc8790969f85210c98e7166905be3893e | JusticeTorkornoo/PasswordManager | /Update_Website.py | 2,735 | 4.21875 | 4 | import sqlite3
import time
import Start_Manager
# #
# This abstraction allows the user to be able to update any website thats on any of their #
# accounts in the database #
# #
def website():
# #
# the variable "conn" was made so you dont have to type in "sqlite3.connect('PasswordManager.db')" #
# every time you wanted to connect to the database. The variable "c" was made to shorten the command #
# connecting to the database even more when setting the cursor where you want to start entering data #
# to the database #
# #
conn = sqlite3.connect('PasswordManager.db')
c = conn.cursor()
# #
# "SELECT * FROM PasswordManager" means that SQlite will select all the data in the databse #
# The for loop is there to traverse through the whole database to print all the accounts in #
# the database #
# #
c.execute("SELECT * FROM PasswordManager ORDER BY Website")
print("Website Username Password")
print()
for row in c.fetchall():
print("{:25} {:30} {:81}".format(row[0], row[1], row[2]))
print("\nWhich account are you updating?")
username = input("Type in the username of the account\n\n")
print()
new_website = input("What's the new website?\n").lower()
c.execute("SELECT * FROM PasswordManager")
c.execute("UPDATE PasswordManager SET Website=? WHERE Username=?", (new_website, username))
# #
# "conn.commit()" will save the previous action in the database and #
# "conn.close()" closes the database so no unwanted data enters the #
# database on accident #
# #
conn.commit()
conn.close()
print("\nUpdated website to " + new_website)
time.sleep(1.5)
Start_Manager.start() |
817d056fe9543ba5a501261f1448d2c581f6dcb9 | Isabel-Mtz/examen | /examen.py | 3,054 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Editor de Spyder
autores:
Luna Gonzales Rosio.
Martinez Garcia Isabel
Este es un archivo temporal.
"""
# =============================================================================
# """
#Primos <generadores> 30 pts
#Realice una generador que devuelva de todos lo numeros primos
#existentes de 0 hasta n-1 que cumpla con el siguiente prototipo:
# [2, 3 ,5 ,7 ]
# =============================================================================
def gPrimo(N):
def primo(i):
if i <= 1:
return False
for j in range (2,i):
if i % j == 0:
return False
return True
i = 0
while (i <= N):
if primo(i):
yield i
i += 1
a= gPrimo(10)
z = [e for e in a]
print (z)
# =============================================================================
#Bada Boom!!! <generadores> 20 pts
#
# Defina un generador que reciba un numero entero positivo mayor a 0 N,
# dicho generador proporciona numero de 1 hasta N
# con las siguientes condiciones:
# 1) si es multiplo de 3 coloque la cadena "Bada"
# 2) si es multiplo de 5 coloque la cadena "Boom!!"
# 3) si es multiplo de 3 y 5 coloque "Bada Boom!!"
# =============================================================================
def genBadaBoom(N):
i = 0
while i < N:
i = i + 1
Bada = i % 3 == 0
Boom = i % 5 == 0
if Bada and Boom:
yield "Bada Boom!!"
elif Bada:
yield "Bada"
elif Boom:
yield "Boom!!"
else:
yield i
a = genBadaBoom(10)
z = [e for e in a]
print(z)
# =============================================================================
# Combinaciones <Comprensin de listas> 30pts
#Una tienda de ropa quiere saber cuantos conjuntos se pueden crear
#a partir de un grupo de 5 camisas (roja,negra,azul,morada y cafe),
#4 pantalones (negro, azul, cafe obscuro y crema) y uno de 4 accesorios
#posibles (cinturon, tirantes, lentes, fedora)
#1) Obtenga una lista con todos los conjuntos posibles e imprimala en pantalla
#2) imprima un mensaje donde mencione la cantidad de conjuntos posibles
# =============================================================================
Z = ['camisa roja','camisa negra','camisa azul','camisa morada','camisa cafe']
Y = ['pantalon negro','pantalon azul','pantalon cafe oscuro','pantalon crema']
W = ['cinturon','tirantes','lentes','fedora']
Combinacion = [[z,y,w] for z in Z for y in Y for w in W ]
print (Combinacion)
print(len(Combinacion))
# =============================================================================
# Fedora? <Comprensin de listas > 15 pts
#Del problema anterior imprima una lista que tenga todos los conjuntos
#que incluyen un sombrero fedora y tambien despliegue su longitud
# =============================================================================
N = [ con for con in Combinacion if con[2]=='fedora']
print(N)
print(len(N))
# ============================================================================= |
d872cac1bb712ccdeaf58ab4f1ab132ba36722a1 | BD20171998/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 178 | 3.890625 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
newdict = a_dictionary.copy()
for i in a_dictionary:
newdict[i] = a_dictionary[i] * 2
return newdict
|
aef724da9ccf4787fa4ae8ad7ab9eaf8988c87af | XinYou-w/analytics-vidhya-demo | /pywebioDemoCodes/basic (without pywebio).py | 540 | 3.75 | 4 | def demo():
age = int(input("Enter your age: "))
year_exp = int(input("Enter your years of experience: "))
if (age >= 16 and age <=20) and (year_exp <=1):
print("Your Expected Salary: {}".format(10000))
elif (age >= 21 and age <=26) and (year_exp >= 2 and year_exp <5):
print("Your Expected Salary: {}".format(40000))
elif (age >= 27) and (year_exp >=5):
print("Your Expected Salary: {}".format(90000))
else:
print("Not in scoped rules!")
if __name__ == "__main__":
demo() |
5266b2f4cf4569269fd2d3a178312b7902b51120 | Baumelbi/SchoolWork | /CloudSeattle911/seattle911.py | 1,210 | 3.8125 | 4 | """This program will call to the seattle 911 api and recieve information realting to
the given latitude and longitude as well as the radius of the circle. The returned
information will be ranked by most common instance to least common"""
#!/usr/bin/env python
# make sure to install these packages before running:
# pip install pandas
# pip install bokeh
import numpy as np
import pandas as pd
import datetime
import urllib
from bokeh.plotting import *
from bokeh.models import HoverTool
from collections import OrderedDict
#the input values are requested here
latitude = float(eval(input("what is your latitude: ")))
longitude = float(eval(input("what is your longitude: ")))
#the hard coded values of our location downtown.
#latitude = 47.608918
#longitude = -122.334732
radius = float(eval(input("what radius would you like in miles: "))*1609)
#the call to the API with the input values
query = ("https://data.seattle.gov/resource/pu5n-trf4.json?$where=within_circle(incident_location,{},{},{})".format(latitude,longitude,radius))
raw_data = pd.read_json(query)
#print(query)
counts = raw_data['event_clearance_group'].value_counts()
print('Crime events by count in your area')
print()
print(counts) |
f3f9498e12cf369fd07da6d3a90e588351b83f78 | zacjohnston/skynet_tools | /traj_code/mathRecipes.py | 387 | 3.578125 | 4 | """Module containing some usefull mathematical recepies."""
import numpy as np
import math
def find_nearest(array,value):
"""Return the nearest array entry to the given value"""
idx = np.searchsorted(array, value)
if math.fabs(value - array[idx-1]) < math.fabs(value - array[idx]):
result = array[idx-1]
else:
result = array[idx]
return result
|
5659a8e391913561686383ccac38230fa0df009e | virginiah894/python_codewars | /8KYU/greet.py | 100 | 3.5 | 4 | def greet(name: str, owner: str) -> str:
return "Hello boss" if name is owner else "Hello guest" |
8d9c8f25221710cb4cecec4e4fd5075dff23726d | PiJoules/lazy-typist | /lazy-typist.py | 4,076 | 3.671875 | 4 | #!/usr/bin/python
import sys
class Coord:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, coord):
dx = abs(self.x - coord.x)
dy = abs(self.y - coord.y)
return dx + dy
class Keyboard:
keyrows = ["qwertyuiop", "asdfghjkl ", "^zxcvbnm ^", " ##### "]
def __init__(self):
self.kb = {}
for y, row in enumerate(self.keyrows):
for x, char in enumerate(row):
self.kb[char] = Coord(x, y)
def getClosestCoord(self, hand, char):
dx = 0
char = char.lower()
charCoord = self.kb[char]
if char == " ":
char = "#"
distances = [0]*4
charCoord = self.kb[char]
for i in range(len(distances)):
tempCoord = Coord(charCoord.x - i, charCoord.y)
distances[i] = hand.coord.distance(tempCoord)
if i != 0 and distances[i] < distances[i-1]:
dx = i
elif char == "^":
distances = [0]*10
for i in range(len(distances)):
tempCoord = Coord(charCoord.x - i, charCoord.y)
distances[i] = hand.coord.distance(tempCoord)
if i != 0 and distances[i] < distances[i-9]:
dx = i
return Coord(charCoord.x - dx, charCoord.y)
def getEffort(self, hand, char):
char = char.lower()
if char == " ":
char = "#"
charCoord = self.kb[char]
distance = 1000000 # some arbitary high value greater than largest distance on keyboard
if char == "#":
for i in range(4):
tempCoord = Coord(charCoord.x - i, charCoord.y)
distance = min(distance, hand.coord.distance(tempCoord))
elif char == "^":
distance = min(hand.coord.distance(charCoord), hand.coord.distance( Coord(charCoord.x - 9, charCoord.y) ))
else:
distance = hand.coord.distance(charCoord)
return distance
class Hand:
def __init__(self, x, y, name):
self.coord = Coord(x, y)
self.name = name
def moveTo(self, x, y):
self.coord.x = x
self.coord.y = y
def moveTo(self, coord):
self.coord = coord
def __str__(self):
return self.name + " hand"
def printMovement(c, hand, effort):
print c, ": Use ", hand, " (Effort: ", effort, ")"
def findPathToEnd(string, kb):
startIndex = 0
nextChar = string[startIndex]
leftHand, rightHand = None, None
if nextChar.isupper():
nextChar = nextChar.lower()
leftHand = Hand(0,2,"left")
rightHand = Hand(kb.kb[nextChar].x, kb.kb[nextChar].y, "right")
startIndex += 1
else:
leftHand = Hand(kb.kb[nextChar].x, kb.kb[nextChar].y, "left")
startIndex += 1
nextChar = string[startIndex]
rightHand = Hand(kb.kb[nextChar].x, kb.kb[nextChar].y, "right")
startIndex += 1
totalEffort = 0
for nextChar in string:
leftHandEffort = kb.getEffort(leftHand, nextChar)
rightHandEffort = kb.getEffort(rightHand, nextChar)
if nextChar.isupper():
leftHandToShift = kb.getEffort(leftHand, "^")
rightHandToShift = kb.getEffort(rightHand, "^")
if leftHandToShift+rightHandEffort < rightHandToShift+leftHandEffort:
leftHand.moveTo(kb.getClosestCoord(leftHand, "^"))
rightHand.moveTo(kb.getClosestCoord(rightHand, nextChar))
printMovement("^", leftHand, leftHandToShift)
printMovement(nextChar, rightHand, rightHandEffort)
totalEffort += leftHandToShift + rightHandEffort
else:
rightHand.moveTo(kb.getClosestCoord(rightHand, "^"))
leftHand.moveTo(kb.getClosestCoord(leftHand, nextChar))
printMovement("^", rightHand, rightHandToShift)
printMovement(nextChar, leftHand, leftHandEffort)
totalEffort += rightHandToShift + leftHandEffort
else:
if leftHandEffort < rightHandEffort:
leftHand.moveTo(kb.getClosestCoord(leftHand, nextChar))
printMovement(nextChar, leftHand, leftHandEffort)
totalEffort += leftHandEffort
else:
rightHand.moveTo(kb.getClosestCoord(rightHand, nextChar))
printMovement(nextChar, rightHand, rightHandEffort)
totalEffort += rightHandEffort
print "Total effort: ", totalEffort
if __name__ == "__main__":
kb = Keyboard()
for i in range(1,len(sys.argv)):
arg = sys.argv[i]
print arg
findPathToEnd(arg, kb)
print "" |
fd7daa7646cdc382f32d2fdc4a00f2cfc8539fd1 | Becojo/adventofcode | /2016/day09.py | 635 | 3.65625 | 4 | data = input().strip()
def decompress(data):
count = 0
while '(' in data:
s = data.index('(')
e = data.index(')') + 1
a, b = map(int, data[s+1:e-1].split('x'))
count += s + a * b
data = data[(e+a):]
return count
def decompress2(data):
if '(' not in data:
return len(data)
count = 0
while '(' in data:
s = data.index('(')
e = data.index(')') + 1
a, b = map(int, data[s+1:e-1].split('x'))
count += s + decompress2(data[e:e+a]) * b
data = data[(e+a):]
return count
print(decompress(data))
print(decompress2(data))
|
0721ee896173ff807377da545f601510789acb6f | dmierm/PythonPY200 | /PythonPY200/Инкапсуляция, наследование, полиморфизм/Практические задания/task4_Figure_polymorphism_inheritance/main.py | 1,109 | 4.25 | 4 | import math
class Figure:
""" Базовый класс. """
def area(self):
print(f"Вызван метод класса {self.__class__.__name__}")
return None
class Rectangle(Figure):
""" Производный класс. Прямоугольник. """
def __init__(self, a, b):
self.a = a
self.b = b
... # TODO определить конструктор и перегрузить метод area
def area(self):
print(f"Вызван метод класса {self.__class__.__name__}")
return self.a * self.b
class Circle(Figure):
""" Производный класс. Круг. """
def __init__(self, r):
self.r = r
... # TODO определить конструктор и перегрузить метод area
def area(self):
print(f"Вызван метод класса {self.__class__.__name__}")
return 3.14 * self.r ** 2
if __name__ == "__main__":
fig = Figure()
fig.area()
rect = Rectangle(5, 10)
rect.area()
circle = Circle(5)
circle.area()
|
87d12e0bf41b5356d89c5ed66e1a4a2c8cad3982 | Mehadisa18/PythonProject | /02_StringsInPython.py | 606 | 3.96875 | 4 | message1 = "Hello this is a string with double quotes"
message2 = 'Hello this is string with single quotes'
message3="Hello this is a string where there are 'single quotes' with in double quotes"
message4='Hello this is a string where there are "double quotes" with in single quotes'
message5='Here I\'m escaping the aposthrophe with a back slash'
message6=""" here is a sentence which contains both 'single' and "double quotes" """
print(message1)
print(message2)
print(message3)
print(message4)
print(message5)
print(message6)
print(message1[1])
# help(str)
str1="hello"
str2="hellor"
print(str1 in str2) |
85e9b72971dece21331d34ced84e13e7c7166471 | rudyn2/cc5114 | /src/neural_network/preprocessing/Normalizer.py | 1,764 | 3.828125 | 4 | import numpy as np
class Normalizer:
"""
This class provides the functionality to performs normalization over a dataset.
"""
def __init__(self):
"""
Constructor for the Normalizer class.
"""
self.data = None
def fit(self, data):
"""
Fits the data to the object.
:param data: A 2D Numpy Array.
"""
assert type(data) == np.ndarray, "The data must be a numpy array"
self.data = data
def transform(self, n_low, n_high):
"""
Transforms the fitted data.
:param n_low: Minimal value required after transformation.
:param n_high: Maximum value required after transformation.
:return: The transformed data.
"""
assert self.data is not None, "The data has not been fitted."
data = self.data.copy()
for column_index in range(data.shape[1]):
column = data[:, column_index]
max_value = np.max(column)
min_value = np.min(column)
data[:, column_index] = (column-min_value)*(n_high-n_low)/(max_value-min_value) + n_low
return data
def fit_transform(self, data, n_low, n_high):
"""
Fits and transforms the data.
:param data: Data to fit.
:param n_low: Minimal value required after transformation.
:param n_high: Maximum value required after transformation.
:return: The transformed data.
"""
self.fit(data)
return self.transform(n_low, n_high)
|
05c4ffe3d5f208172b90c6b4af2cc5c231185ecd | davidecarzaniga/nba-py | /locations.py | 161 | 3.515625 | 4 | import csv
reader = csv.reader(open(r"db-locations.csv"), delimiter=',')
filtered = filter(lambda p: 'Andre Iguodala' == p[3], reader)
for row in filtered:
print(row) |
22fc65ec8afc471fa56337c2b74e81ca175d856a | benwarner/euler | /primes.py | 3,505 | 3.953125 | 4 | import math
import copy
#def phi(n):
def prime_powers(n, primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]):
"""
Like the factorize method but returns a list of tuples
where the first entry is a prime and the second is the
number of occurances of that prime.
"""
prime_list = factorize(n)
previous_prime = prime_list[0]
e = 1
prime_power_list = []
for p in prime_list[1:]:
if previous_prime == p:
e += 1
else:
prime_power_list.append((previous_prime, e))
previous_prime = p
e = 1
prime_power_list.append((previous_prime, e))
return prime_power_list
def list_factors(n, primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]):
factors = recurfactorize(n, primes)
factorstrlist = factors.split()
factorlist = []
for factor in factorstrlist:
factorlist.append(int(factor))
return factorlist
def recurfactorize(n, primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]):
"""
Factorize by (recursive) trial division from a list of primes.
"""
factors = ""
if n == 1:
return ""
i = 0
try:
while primes[i] <= math.sqrt(n):
if n % primes[i] == 0:
factor = primes[i]
break
else:
i += 1
if primes[i] <= math.sqrt(n):
factors += (" " + str(factor) + " " + str(factorize(n/primes[i], primes)))
#factors.extend([factor, (factorize(n/primes[i], primes))])
return factors
else:
return str(n)
except IndexError:
print "I'm sorry, but your list of primes is too short."
return ""
def factorize(n, primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]):
"""
Factorize by trial division from a list of primes.
"""
if primes[-1] < math.sqrt(n):
primes = genprimelisttd(math.sqrt(n), primes)
factors = []
while n > 1:
i = 0
try:
while n % primes[i] != 0 and primes[i] <= math.sqrt(n):
i += 1
if n % primes[i] == 0:
factors.append(primes[i])
n = n / primes[i]
else: # We must have reached the square root.
factors.append(n)
break
except IndexError as err:
# We came just below the square root (e.g. 1693 is prime and math.sqrt(1693 == 41.146)
factors.append(n)
break
return factors
def isprime(n):
"""
Checks if n is prime by one iteration of Fermat's little theorem.
"""
return True if 2 ** (n - 1) % n == 1 else False
def genprimelistflt(maxprime, primes = [2, 3]):
"""
Generates a list of primes by Fermat's little theorem.
"""
n = primes[::-1][0]
while n <= maxprime:
if isprime(n):
primes.append(n)
n = n + 2
return primes
def genprimelisttd(maxprime, primes = [2, 3]):
"""
Generates a list of primes by trial division.
"""
if primes[0: 2] != [2, 3]: # Just a little data validation.
primes=[2, 3]
n = primes[::-1][0] + 2
while n <= maxprime:
prime = True
i = 0
while primes[i] <= math.sqrt(n):
if n % primes[i] == 0:
prime = False
break
i += 1
if prime:
primes.append(n)
n = n + 2
return primes
|
d6d9d362b9ea8031cb48480100ef987554cfbfcf | shindeswapnil/46-Exercise | /8.py | 306 | 4.28125 | 4 | #Define a function is_palindrome() that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True.
def is_palindrome(s):
s1=s[::-1]
if s==s1 :
return True
else :
return False
s=input('Enter String : ')
print(is_palindrome(s))
|
e8091cc6b1b0baf4a706b249f1d565bd4b4343b1 | rosteeslove/bsuir-4th-term-python-stuff | /numerical_analysis_methods/nonlineqs/rootapprox/newtons_method.py | 683 | 3.9375 | 4 | """
This module contains the calculate_root method to approximate
polynomial's root in an interval using Newton's method.
"""
from numpy.polynomial.polynomial import Polynomial
from rootapprox import simple_iteration_method as sim
def calculate_root(f: Polynomial, a, b, eps):
"""
Return root approximation calculated with Newton's method as well
as number of iterations made to calculate it.
Root of polynomial f is approximated in [a, b] interval until
error is smaller than epsilon eps.
"""
assert f(a)*f(b) < 0
df = f.deriv()
def newtons_lambda(x):
return -1 / df(x)
return sim.calculate_root(f, newtons_lambda, a, b, eps)
|
415d899572427dd56d1345cb15d7ec73ec4a2c59 | yost1219/python | /python/labs/lab2d-f.py | 1,701 | 4.4375 | 4 | >>> #lab2d
>>> def reverse():
... userInput = raw_input("Tell me something good.\n")
... reverseInput = userInput[::-1]
... reverseCaps = reverseInput.upper()
... print reverseCaps
... return
...
>>> def reverse():
... print raw_input("Tell me something good.\n")[::-1].upper()
... return
...
>>> #lab2e
>>> def countWords() :
... userInput = raw_input("I'll count your words.\n")
... word = userInput.split(" ")
... print len(word)
... return
...
"""
Author: Yost
Title: Lab 2F
Date: 5 Sep 2018
Lab 2F: Man A Rag
Instructions:
Write a program that will be able to check if two words (strings) are anagrams.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase
The program should include:
All proper comments
Needed docstrings
User input (only expecting one user input due to not having gone over loops yet)
"""
>>> def anagram():
... #get two words from user to compare
... print "Enter two words to compare.\n"
... word1 = raw_input("Input the first word.\n")
... word2 = raw_input("Input the second word.\n")
... #convert to all caps to take case out of the situation
... word1 = word1.upper()
... word2 = word2.upper()
... #order the letters of the words
... list1 = sorted(word1)
... list2 = sorted(word2)
... #compare the two lists to see if they are equal or not
... #if they are equal then say so, if not then say that
... if list1 == list2:
... print "The two words are anagrams."
... else:
... print "The two words are not anagrams."
... return |
9108a5bc1f4c9011ca673c09f328cc6dae8ea961 | mhyang123/tensorflow_test1 | /calc/__init__.py | 357 | 3.578125 | 4 | from calc import Calc
def main ():
calc=Calc(3,7)
print("{}+{}={}".format(calc.first,calc.second,calc.sum()))
print("{}*{}={}".format(calc.first,calc.second,calc.mul()))
print("{}-{}={}".format(calc.first,calc.second,calc.minus()))
print("{}/{}={}".format(calc.first,calc.second,calc.div()))
if __name__ == '__main__':
main()
|
bed21fdbca48ef2a65f56e88535af24680062d20 | cruzortiz99/python-course | /cap_3/exercise/solution.py | 8,297 | 3.96875 | 4 | # 1. Crear una función encargada de sumar dos números
from functools import reduce
def add(first, second):
return first + second
# 2. Crear una función encargada de sumar n números enteros
def add(*nums):
result = 0
for num in nums:
result = result + num
return result
# 3. Crear una función que devuelva un valor cuando una condición se cumpla y
# otro valor cuando la condición no se cumpla. Ejemplo:
# ifOrElse(whenIsTrue, whenIsFalse, condition)
# ifOrElse("hola", "chao", True) -> "hola"
# ifOrElse("hola", "chao", False) -> "chao"
def ifOrElse(whenSuccess, whenFails, condition):
if condition:
return whenSuccess
else:
return whenFails
# 4. Crear una función encargada de retornar un valor cuando el retorno de
# una función es cierta y otro valor cuando el retorno de una función es
# falsa. Ejemplo:
# ifOrElse("hola", "chao", lambda: True) -> "hola"
# ifOrElse("hola", "chao", lambda: False) -> "chao"
def ifOrElse(whenSuccess, whenFails, condition):
if condition():
return whenSuccess
else:
return whenFails
# 5. Crear una función encargada de ejecutar una función cuando el retorno
# de una función es cierta y ejecuta otra cuando el retorno de una función
# es falsa. Ejemplo:
# ifOrElse(lambda: "hola", lambda: "chao", lambda: True) -> "hola"
# ifOrElse(lambda: "hola", lambda: "chao", lambda: False) -> "chao"
def ifOrElse(whenSuccess, whenFails, condition):
if condition():
return whenSuccess()
else:
return whenFails()
# if 15 > 16:
# do_some_work()
# else:
# do_nothing()
# ifOrElse(do_some_work, do_nothing, slow_condition)
# 6. Hacer de las funciones anteriores, de ejecución perezosa o funciones
# de orden superior.
def addLazy(*nums): return lambda: add(nums)
def ifOrElseLazy(whenSuccess, whenFails, condition):
def container():
if condition():
return whenSuccess()
else:
return whenFails()
return container
# lazy_result = ifOrElseLazy(do_some_work, do_nothing, slow_condition)
# ifOrElse(do_some_work,do_nothing,slow_condition)
# ...
# lazy_result()
# 7.Dado:
# list = [
# {
# "name": "Cruz",
# "last_name": "Ortiz",
# "age": 29,
# "friends": [],
# "car": {"name": "Logan", "type": "sedan"}},
# {
# "name": "German",
# "last_name": "Montero",
# "age": 63,
# "friends": [{
# "name": "Cruz",
# "last_name": "Ortiz",
# "age": 29}],
# "car": {"name": "Mustang", "type": "deportivo"}},
# {
# "name": "Martin",
# "last_name": "Palermo",
# "age": 42,
# "friends": [],
# "car": {"name": "Cherokee", "type": "camioneta"}},
# {
# "name": "John",
# "last_name": "English",
# "age": 72,
# "friends": [],
# "car": {"name": "Aveo", "type": "sedan"}},
# {
# "name": "Indiana",
# "last_name": "Jones",
# "age": 55,
# "friends": [],
# "car": {"name": "Mustang", "type": "deportivo"}},
# {
# "name": "Luke",
# "last_name": "Skywalker",
# "age": 56,
# "friends": [{
# "name": "Cruz",
# "last_name": "Ortiz",
# "age": 29,
# },{
# "name": "German",
# "last_name": "Montero",
# "age": 63,
# }],
# "car": {"name": "Cherokee", "type": "camioneta"}}
# ]
# 7.1. Contar la cantidad de persona en la lista.
#
# 7.2. Contar la cantidad de personas que poseen amigos.
#
# 7.3. Contar la cantidad de personas que poseen el mismo tipo de carro.
#
# 7.4. Mostrar una lista de los carros que se poseen
#
# 7.5. Convierta los diccionarios en la lista en un tipo personalizado
#
# persons = [
# {
# "name": "Cruz",
# "last_name": "Ortiz",
# "age": 29,
# "friends": [],
# "car": {"name": "Logan", "type": "sedan"}},
# {
# "name": "German",
# "last_name": "Montero",
# "age": 63,
# "friends": [{
# "name": "Cruz",
# "last_name": "Ortiz",
# "age": 29}],
# "car": {"name": "Mustang", "type": "deportivo"}},
# {
# "name": "Martin",
# "last_name": "Palermo",
# "age": 42,
# "friends": [],
# "car": {"name": "Cherokee", "type": "camioneta"}},
# {
# "name": "John",
# "last_name": "English",
# "age": 72,
# "friends": [],
# "car": {"name": "Aveo", "type": "sedan"}},
# {
# "name": "Indiana",
# "last_name": "Jones",
# "age": 55,
# "friends": [],
# "car": {"name": "Mustang", "type": "deportivo"}},
# {
# "name": "Luke",
# "last_name": "Skywalker",
# "age": 56,
# "friends": [{
# "name": "Cruz",
# "last_name": "Ortiz",
# "age": 29,
# },{
# "name": "German",
# "last_name": "Montero",
# "age": 63,
# }],
# "car": {"name": "Cherokee", "type": "camioneta"}}
# ]
persons = [
{
"name": "Cruz",
"last_name": "Ortiz",
"age": 29,
"friends": [],
"car": {"name": "Logan", "type": "sedan"}},
{
"name": "German",
"last_name": "Montero",
"age": 63,
"friends": [{
"name": "Cruz",
"last_name": "Ortiz",
"age": 29}],
"car": {"name": "Mustang", "type": "deportivo"}},
{
"name": "Martin",
"last_name": "Palermo",
"age": 42,
"friends": [],
"car": {"name": "Cherokee", "type": "camioneta"}},
{
"name": "John",
"last_name": "English",
"age": 72,
"friends": [],
"car": {"name": "Aveo", "type": "sedan"}},
{
"name": "Indiana",
"last_name": "Jones",
"age": 55,
"friends": [],
"car": {"name": "Mustang", "type": "deportivo"}},
{
"name": "Luke",
"last_name": "Skywalker",
"age": 56,
"friends": [{
"name": "Cruz",
"last_name": "Ortiz",
"age": 29,
}, {
"name": "German",
"last_name": "Montero",
"age": 63,
}],
"car": {"name": "Cherokee", "type": "camioneta"}}
]
# 7.1
print(f"7.1 Cantidad de personas: {len(persons)}")
# 7.2
def if_has_friend(person):
return len(person["friends"]) > 0
person_with_friends = len(
list(filter(if_has_friend, persons)))
print(f"7.2 Cantidad de personas con amigos: {person_with_friends}")
# 7.3
def groupByCar(groups, person_dict):
car_name = person_dict["car"]["name"]
if car_name in groups:
groups[car_name] = groups[car_name] + [person_dict]
else:
groups[car_name] = [person_dict]
return groups
def totalizeGroups(persons_group_by_car):
totalize = {}
for car_name in persons_group_by_car:
totalize[car_name] = len(
persons_group_by_car[car_name])
return totalize
print(f"""7.3 Cantidad de personas agrupadas por carro: {
totalizeGroups(reduce(groupByCar, persons, {}))}""")
# [{...}, {...}]
# {"Logan": [{...}], "Mustang": [{...}]}
# {"Logan": 85, "Mustang": 8}
# 7.4
def dischardIfExists(acc, current_car):
filtered_car_name = list(map(lambda car: car["name"], acc))
if current_car["name"] in filtered_car_name:
return acc
else:
return acc + [current_car]
cars = reduce(dischardIfExists, list(
map(lambda person: person["car"], persons)), [])
print(f"7.4 Carros que se poseen: {list(map(lambda car: car['name'], cars))}")
# 7.5
class Person:
def __init__(self, name, last_name, age, car=None, friends=[]):
self.name = name
self.last_name = last_name
self.age = age
self.car = car
self.friends = friends
class Car:
def __init__(self, name, type):
self.name = name
self.type = type
def dictToPersons(person_dict):
return Person(
name=person_dict["name"],
last_name=person_dict["last_name"],
age=person_dict["age"],
car=Car(
name=person_dict["car"]["name"],
type=person_dict["car"]["type"]),
friends=list(map(
lambda friend: Person(
name=friend["name"],
last_name=friend["last_name"],
age=friend["age"]
),
person_dict["friends"])))
persons_in_class = list(map(dictToPersons, persons))
print("7.5 Personas con clases: ", list(
map(lambda person: person.name, persons_in_class)))
|
283ae88e3b896f402ca1729ede8c5b5fd4872fee | anshulagl/Art-Gallery-Simulation | /triangle.py | 1,066 | 3.9375 | 4 |
from point import Point
from side import Side
class Triangle(object):
""" Class representing a Triangle that is composed by
three Point objects
"""
def __init__(self, u, v, w):
if not all(isinstance(point, Point) for point in (u, v, w)):
raise TypeError("u, v, w must be Point objects", (u, v, w))
self.u, self.v, self.w = u, v, w
def __repr__(self):
return "[(%s, %s), (%s, %s), (%s, %s)]" \
% (self.u.x, self.u.y, self.v.x, self.v.y, self.w.x, self.w.y)
def __iter__(self):
yield self.u
yield self.v
yield self.w
def sides(self):
return (Side(self.u, self.v), Side(self.v, self.w), Side(self.w, self.u))
def opposite(self, side):
if self.u == side.p0:
if self.v == side.p1:
return self.w
else:
return self.v
elif self.u == side.p1:
if self.v == side.p0:
return self.w
else:
return self.v
return self.u
|
703554f2964859d5e580ae03480e1dec83d026ec | ryan-moll/SNKRSbot | /nike.py | 1,338 | 3.546875 | 4 | import urllib.request
from bs4 import BeautifulSoup
# specify the url
quote_page = 'https://www.nike.com/launch/?s=upcoming'
# query the website and return the html to the variable 'html'
with urllib.request.urlopen(quote_page) as response:
html = response.read()
# parse the html using beautiful soup and store in variable 'soup'
soup = BeautifulSoup(html, 'html.parser')
# gather the list of upcoming shoes and dates
nameStack = []
for shoe in soup.find_all('h3', {'class':'ncss-brand u-uppercase text-color-grey mb-1-sm mb0-md mb-3-lg fs12-sm fs14-md'}):
nameStack.append(shoe.text[:-1])
colorStack = []
for shoe in soup.find_all('h6', {'class':'ncss-brand u-uppercase fs20-sm fs24-md fs28-lg'}):
colorStack.append(shoe.text[:-1])
monthStack = []
for shoe in soup.find_all('p', {'class':'mod-h2 ncss-brand u-uppercase fs19-sm fs28-md fs34-lg'}):
monthStack.append(shoe.text)
dayStack = []
for shoe in soup.find_all('p', {'class':'mod-h1 ncss-brand test-day fs30-sm fs40-md'}):
dayStack.append(shoe.text)
# format the list of shoes to be sent to twitter.py
stack = []
shoeInfo = '{} {} - {} {}'
for item in zip(nameStack, colorStack, monthStack, dayStack):
stack.append(shoeInfo.format(item[0], item[1], item[2], item[3]))
size = len(stack)
print('Successfully retrieved list of upcoming sneaker releases.') |
352d7ff4033dbb05cfdec83dae6371b6fa3e09a0 | MayThandaSoe/test1 | /Documents/python exercise/GUI (Day 2)/GUI_day2/kilo_converter(label).py | 2,566 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 17:48:00 2020
@author: Yu Hlaing Win
"""
import tkinter
class KiloConvertor():
def __init__(self):
self.main_window = tkinter.Tk()
#Create two frames
self.top_frame= tkinter.Frame(self.main_window)
self.mid_frame=tkinter.Frame(self.main_window)
self.bottom_frame=tkinter.Frame(self.main_window)
#Create the top frame's widgets
self.kilo_label=tkinter.Label(self.top_frame,
text='Enter kilometers:')
self.kilo_entry=tkinter.Entry(self.top_frame,
width=10)
#Pack the frames
self.kilo_label.pack(side='left')
self.kilo_entry.pack(side='left')
#Create the widgets for middle frame
self.mile_label=tkinter.Label(self.mid_frame,
text='Converted to miles: ')
#need create object for StringVar()
#to assosiate with an output label
#Use the set method to store a stirng of blank characters
self.output= tkinter.StringVar()
#Create out put lavel
self.miles_output=tkinter.Label(self.mid_frame,
textvariable=self.output)
#Pack the middle frame widges
self.mile_label.pack(side='left')
self.miles_output.pack(side='left')
#Create the buttons in bottom frame
self.cal_button=tkinter.Button(self.bottom_frame,
text='Convert',
command=self.convert)
self.quit_button=tkinter.Button(self.bottom_frame,
text='Quit',
command=self.main_window.destroy)
#Pack the buttons
self.cal_button.pack(side='left')
self.quit_button.pack(side='left')
#Pack the frames
self.top_frame.pack()
self.mid_frame.pack()
self.bottom_frame.pack()
#Enter the mainloop
tkinter.mainloop()
def convert(self):
#kilo=float(input('Enter kilometer:'))
kilo=float(self.kilo_entry.get())
#convert to miles
miles=kilo*0.6214
#Display the results
self.output.set(miles)
kilo_convert=KiloConvertor()
|
36c907ac4273cd927e1a5764ed1a715375d55874 | jerkuebler/pyeuler | /11-20/highdivtrinum.py | 425 | 3.703125 | 4 | def find_triangular_number(factors):
divis = []
position = 0
num = 0
while len(divis) < factors:
divis = []
position += 1
num += position
for i in range(1, int(num**0.5) + 1):
if num % i == 0:
divis.append(i)
divis.append(num // i)
print(divis)
divis = set(divis)
return num
print(find_triangular_number(500)) |
3269a836052aa3399acdf0490398dc11989ddb8b | Soe-Htet-Naung/CP1404PPrac | /Prac03/password_check.py | 233 | 3.75 | 4 | def main():
password = input("Please enter Password: ")
get_password(password)
def get_password(password):
output = ""
for i in password:
output += "*"
print(output)
if __name__ == '__main__':
main() |
81aa41c2c910a64bbd446093ad8172930108a9b1 | CodeMan31/Lab12AdvEmb_JustinLandry | /Part2.py | 1,088 | 3.734375 | 4 | import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
# cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
cv.imwrite('exitimage.jpg', gray)
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
# This program could be very useful in variety of applications. Being able
# to capture images means you can do things with that image like face recognition,
# you could use to it work as vision for a robot, you could use it for motion
# control, etc. In conclusion this could be a very fundamental part of a variety of
# very cool advanced applications. #
|
e550206dfcc98509ef54953873864b6329e6f9f3 | fingerman/python_fundamentals | /python-fundamentals/1.2_PersonInfo.py | 180 | 3.859375 | 4 | name = input()
age = int(input())
town = input()
salary = float(input())
print(name + " is " + str(age) + " years old, is from " + town + " and makes $" + str(round(salary, 2)))
|
9762afa11252796229d6afcb5c30f84c436e8a46 | muhammadosmanali/HackerRank | /Python/4. Sets/Introduction to Sets.py | 301 | 4.03125 | 4 | def average(array):
array = list(set(array))
total = 0
for x in array:
total += x
result = total / len(array)
return round(result, 3)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) |
10762752d4441afab2196bbb707336f2c6c41c16 | S-O-S/Python-Programming-A-Concise-Introduction | /Problem Set Solution/ProblemSet1/problem1_3.py | 106 | 3.671875 | 4 | def problem1_3(n):
my_sum = 0
for x in range(1,n+1):
my_sum = my_sum + x
print(my_sum) |
bf6409efa7a7a16e5b0134004a97821e5bf7fd53 | namanofficial10/pymycaptainnaman | /circle_area.py | 121 | 4.125 | 4 | a = float(input("Input the radius of the circle : "))
print(f"The area of the circle with radius {a} is: {(22/7)*a*a}")
|
2c8daa3c6497329990feb5703a92e8054e8e0e32 | JaiRaga/FreeCodeCamp-Data-Structures-and-Algorithms-in-Python | /Basic_Algorithm_Scripting/WhereDoIBelong.py | 401 | 3.515625 | 4 | def getIndexToIns(lis, num):
if len(lis) == 0:
return 0
for i in range(len(lis)):
if lis[i] >= num:
return i
elif i == len(lis)-1:
return len(lis)
print(getIndexToIns([10, 20, 30, 40, 50], 35))
print(getIndexToIns([10, 20, 30, 40, 50], 30))
print(getIndexToIns([3, 10, 5], 3))
print(getIndexToIns([2, 5, 10], 15))
print(getIndexToIns([], 1)) |
5b3ef3c3ae8c6affd709ecbeda1bed47492c28c4 | Manuelpv17/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,585 | 4.15625 | 4 | #!/usr/bin/python3
"""function that prints My name is <first name> <last name>
"""
def matrix_divided(matrix, div):
"""[summary]
Arguments:
matrix {int, float} --
matrix to be divided
div {int, float} -- division number
Raises:
TypeError: matrix must be a
matrix (list of lists) of integers/floats
ZeroDivisionError: division by zero
TypeError: Each row of the matrix must have the same size
TypeError: div must be a number
Returns:
[type] -- [description]
"""
new = []
if type(div) not in [int, float]:
raise TypeError(
"div must be a number")
if div == 0:
raise ZeroDivisionError("division by zero")
if type(matrix) is not list or type(matrix[0]) is not list:
raise TypeError(
"matrix must be a matrix (list of lists) of integers/floats")
size = len(matrix[0])
ms = "matrix must be a matrix (list of lists) of integers/floats"
for row in matrix:
new_row = []
if type(row) is not list:
raise TypeError(
"matrix must be a matrix (list of lists) of integers/floats")
if size != len(row):
raise TypeError("Each row of the matrix must have the same size")
for item in row:
if type(item) not in [int, float]:
raise TypeError(ms)
new_row.append(round(item / div, 2))
new.append(new_row)
return new
|
974cf20c28cb338f1fa2088aa644b5ebeffa8a1a | CarlosZS9/PythonCurso | /prueba_excepsiones2.py | 1,064 | 4.09375 | 4 | def divide():
try:
op1=float((input("Introduce el primer numero")))
op2=float((input("Introduce el segundo numero")))
print("La division es: "+ str(op1/op2))
except ValueError:
print("El valor es erroneo")
except ZeroDivisionError:
print("No se puede dividir entre 0")
#finally siempre se ejecuta
finally:
print("Calculo finalizado")
#divide()
#Raise: Mandamos errores personalizados
"""def evaluaEdad(edad):
if edad<0:
raise MipropioError("No se permiten edades negativas")
if edad<20:
return "eres muy joven"
elif edad<40:
return "eres joven"
elif edad<65:
return "eres maduro"
elif edad<100:
return "Cuídate..."
print(evaluaEdad(-15))"""
import math
def calculaRaiz(num1):
if num1<0:
raise ValueError ("El numero no puede ser negativo")
else:
return math.sqrt(num1)
op1=(int(input("Introduce un numero: ")))
try:
print(calculaRaiz(op1))
except ValueError as ErrorDeNumeroNegativo:
print(ErrorDeNumeroNegativo)
print("programa terminado")
|
223282303cdd226c1f03e90dd45486022990fbe3 | shabbirkhan0015/python_programs | /list2add.py | 224 | 3.828125 | 4 | s=[]
def add(l1,l2):
s=[[0]*2 for i in range(3)]
for i in range(0,len(l1)):
for j in range(0,len(l1[i])):
s=s+s[i][j]
return(s)
print(add([[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]))
|
d4b490f7d33b98c717f1bcb98598096053218105 | AlphaAlpacaa/Project-Euler-s-Solutions | /Project Euler's Solutions/Pandigital_prime.py | 940 | 4.0625 | 4 | """pandigital olan en büyük asal sayı kaçtır?(padigital 1 den n e kadar
bütün rakamları 1 kez içeren)
9 veya 8 basamaklı olsaydı 3 e bölünür sayımız en fazla 7 basamaklı olacak."""
liste = []
def pandigital_Controller(number):
if "1" in str(number):
if "2" in str(number):
if "3" in str(number):
if "4" in str(number):
if "5" in str(number):
if "6" in str(number):
if "7" in str(number):
liste.append(number)
def prime_Number(number):
sayac = 0
for i in range(2,number):
if(number % i == 0):
sayac += 1
if sayac == 0:
return True
for number in range(7000000,8000000):
pandigital_Controller(number)
result_List = []
for number in liste:
if prime_Number(number) == True:
result_List.append(number)
print(max(result_List)) |
0ad29d8514c21fffc9d356255adbc9aaa2ebc771 | Userbash/my_python | /generate_permutation.py | 462 | 3.8125 | 4 | #!/usr/bin/python
def find(number, A):
for x in A:
if number == x:
return True
return False
def generate_permutation(N:int, M:int=-1, prefix=None):
M = N if M == -1 else M
prefix = prefix or []
if M == 0:
print(*prefix)
return
for number in range (1, N+1):
if find(number, prefix):
continue
prefix.append(number)
generate_permutation(N, M-1, prefix)
prefix.pop()
generate_permutation(3) |
2c69884794d96e40eca44f499aeb49a99b723e33 | jalisdotco/Hangman | /hangman.py | 536 | 3.59375 | 4 | import random, string, sys
bank = ['print','bank','prints','printing','printed','printer','letter',\
'kalashkinov','honduras','yeti','roaming','backup','ohkay']
bank = ['hello there']
letters = string.ascii_lowercase
words = random.choice(bank)
##star = '*' * len(words)
guesses = 0
end = 'game over'
# Added a really Cool
print words
#
print guesses
##print star
while guesses != 10:
command = raw_input("Your guess:")
if command in ['quit','exit']:
sys.exit(0)
guesses += 1
print guesses
|
5be924224931100b1962c00d7bbe0a76bc10dde1 | dymodi/tensorflow_basics | /dnn_on_mnist_with_tf.py | 1,933 | 3.859375 | 4 | # A tutorail code for learning TensorFlow
# Based on the tutorial provided by TensorFLow
# Use deep NN on MNIST datt
# Yi DING @ 01/05/18
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# ==================== First section, simple softmax model
# Load MNIST Data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# Note that here "mnist" is a lightweight class called "Datasets"
# Start TensorFlow InteractiveSession
sess = tf.InteractiveSession()
# Build placeholders
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
# Variables
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Initialize variables
sess.run(tf.global_variables_initializer())
# Build graph (model)
y = tf.matmul(x, W) + b
# Build loss function
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# Train the model
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# Note that the return "train_step" is an "Operation"
# Hence training can be conducted by repeatedly run the "Operation"
for _ in range(1000):
batch = mnist.train.next_batch(100)
train_step.run(feed_dict={x: batch[0], y_: batch[1]})
# Evaluate the model (Build evaluation graph)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
# ==================== Second section, multilayer CNN
# Handy functions
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial)
# Convolution and pooling
def con2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
|
f56af69fdb69f2e6abd2b1d01f14e4fc766ce05b | KenSH77/LearnPython | /ex29.py | 900 | 4.25 | 4 | people = 40
cats = 30
dogs = 41
if people < cats:
print "Too many cats! the world is doomed!"
if people > cats:
print "Not many cats! the world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry"
dogs +=5
if people >=dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
print "Now the code is added if elif"
people = 30
cars = 40
buses= 40
if cars > people:
print "We should take the cars"
elif cars < people:
print "We should not take the cars"
else:
print "we cannot decide."
if buses > cars:
print "Thats too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
|
59c6bc5f134f7fbb901f70849b6219426f78bb98 | jingong171/jingong-homework | /闫凡/第一次作业/第一次作业-金融工程17-1-2017310390-闫凡/循环用法:水仙花数.py | 220 | 3.78125 | 4 | print("三位数中的水仙花数有:")
for number in range(100,1000):
a=number%10
b=(number%100-a)/10
c=(number-a-b*10)/100
num=a**3+b**3+c**3
if num==number:
print(str(number)+" ")
|
4030ec6d144efd3792e3ef0f48d36bddf77bc0cf | carlosfabioa/TDS_exercicios_logica_programacao | /3-Lacos de repeticao/Enquanto/exercicio1.py | 601 | 4.09375 | 4 | '''
Apresentar todos os valores numéricos inteiros ímpares situados na faixa de 0 a 20.
Para verificar se o número é ímpar, efetuar dentro da malha a verificação lógica
desta condição com a instrução se, perguntando se o número é ímpar; sendo, mostre-o;
não sendo, passe para o próximo passo.
'''
#iniciamos um contador para usar como critério de parada
contador = 0
while contador <= 20:
if contador %2 != 0:
print(contador)
# a cada laço acrescentamos mais um à variável contador.
# quando a variavel contador atingir 20 o laço para
contador += 1
|
bc727408cac31114be43b131bc0a4c86c6f88fe4 | andro-demir/ModernSignalProcessingAlgorithms | /reverseLevinson/main.py | 1,106 | 3.78125 | 4 | #A is a vector of doubles,
#first number corresponds to z^0, second z^-1, third z^-2 etc...
#You must enter 0 if a term does not exist.
import numpy as np
from fractions import Fraction
# For problem 1:
H = np.array([1, 2, Fraction(1,3)])
# For H1 in problem 2:
H1 = np.array([1, 0.4, -1.2, 2])
# For H2 in problem 3:
H2 = np.array([1, -0.6, 0.2, 0.5])
# Solves the lattice coefficients K recursively:
# Prints from K_n, K_n-1, ..., to K1.
def reverseLevinson(FIRfilter):
filter_length = len(FIRfilter)
if filter_length >= 2:
k = FIRfilter[-1]
if filter_length == 2 and FIRfilter[0] > 0:
k = abs(k)
print(k)
FIRfilter = (FIRfilter - k * FIRfilter[::-1]) / (1 - k**2)
FIRfilter = FIRfilter[:filter_length - 1]
reverseLevinson(FIRfilter)
print("Lattice coefficients of problem 1")
reverseLevinson(H)
print("-----------------------------------")
print("Lattice coefficients of H1 in problem 2")
reverseLevinson(H1)
print("-----------------------------------")
print("Lattice coefficients of H2 in problem 2")
reverseLevinson(H2) |
08c29ba19053f72eea5ffe94481f9973e3aed87b | yatashashank/python | /ass-1/first.py | 750 | 4.15625 | 4 | import re
p=raw_input("enter a password : ")
if len(p)>16 or len(p)<6 :
print "not a valid password. Make sure length of password should be in range 6-16 characters"
elif p.isalnum()==True :
print"not a valid password. should contain atleat one digit"
elif not re.search("[[$@!*]",p):
print " not a valid password. Make sure it contain atleast one of this $@!* special charceter"
elif not re.search("[a-z]",p) :
print " not a valid password. Make sure it contain atleast one lower case letter"
elif not re.search("[A-Z]",p):
print " not a valid password. Make sure it contain atleast one upper case letter"
elif re.search("\s",p):
print "not a valid password. Make sure there is no spaces "
else :
print "valid password"
|
f3bb3d9848a321f760d6dd8bb64a9f8a99c4201e | BigSamu-Coding-Dojo-Python-Assignments/Functions_Basic_I | /Functions_Basic_I.py | 5,496 | 4.125 | 4 |
#Excercise_1
def Excercise_1():
def a():
return 5
print(a())
# Function a() return value 5. Value 5 is printed on the terminal
#Excercise_2
def Excercise_2():
def a():
return 5
print(a()+a())
# Function a() return value 10. Value 10 is printed on the terminal
#Excercise_3
def Excercise_3():
def a():
return 5
return 10
print(a())
# Function a() return value 5. Value 5 is printed on the terminal. Second return statement is not considered.
#Excercise_4
def Excercise_4():
def a():
return 5
print(10)
print(a())
# Function a() return value 5. Value 5 is printed on the terminal. Stament "print(10)" in function a() is not executed because it is after the return statement
#Excercise_5
def Excercise_5():
def a():
print(5)
x = a()
print(x)
# Function a() does not return anything. It only print 5 on the terminal when is executed. Value of "x" is undefined. On terminal the values that are going to appear are 5 and "none"
#Excercise_6
def Excercise_6():
def a(b,c):
print(b+c)
print(a(1,2) + a(2,3))
# Function a() does not return anything. It only print the sum of two given arguments on the terminal when is executed. On terminal the values that are going to appear are 3, 5 and an error. The last one is because python does not support the sum of two 'NoneType' variables
#Excercise_7
def Excercise_7():
def a(b,c):
return str(b)+str(c)
print(a(2,5))
# Function a() return concatenation of two numbers converted to a string. On terminal the values that are going to appear is 25.
#Excercise_8
def Excercise_8():
def a():
b = 100
print(b)
if b < 10:
return 5
else:
return 10
return 7
print(a())
# Function a() return output of else statement (b>10) which is 10. On terminal the values that are going to appear are 100 and 10 (print(b) and print(a()) functions respectivetly). Third return statement (return 7) is not considered because it is after the other two return statements which are inside an if/else block
#Excercise_9
def Excercise_9():
def a(b,c):
if b<c:
return 7
else:
return 14
return 3
print(a(2,3))
print(a(5,3))
print(a(2,3) + a(5,3))
# Function a() return the following outputs on for each statement called: 7 (a(2,3)) and 14 (a(5,3)). On terminal the values that are going to appear are 7 (print(a(2,3))), 14 (print(a(5,3))) and 21 (print(a(2,3))+print(a(5,3))). Third return statement (return 3) is not considered because it is after the other two return statements which are inside an if/else block
#Excercise 10
def Excercise_10():
def a(b,c):
return b+c
return 10
print(a(3,5))
# Function a() return the sum of two arguments. On terminal the value that is going to appear is 8 (print(a(3,5))). Second return statement (return 10) is not considered because it is after the first return statement (function finish when first return statement is run)
#Excercise 11
def Excercise_11():
b = 500
print(b)
def a():
b = 300
print(b)
print(b)
a()
print(b)
# Function a() does not return anything. On terminal the value that is going to appear are: 500 (first print(b) statement), 500(third print(b) statement), and 300 (third print(b) statement isnisde a() function) and 500 (fourth print(b) statement). Function a() does not changes value of b variable outside function a().
#Excercise 12
def Excercise_12():
b = 500
print(b)
def a():
b = 300
print(b)
return b
print(b)
a()
print(b)
# Function a() returns the value 300. On terminal the value that is going to appear are: 500 (first print(b) statement), 500(third print(b) statement), and 300 (third print(b) statement isnisde a() function) and 500 (fourth print(b) statement). Function a() does not changes value of b variable outside function a().
#Excercise 13
def Excercise_13():
b = 500
print(b)
def a():
b = 300
print(b)
return b
print(b)
b=a()
print(b)
# Function a() returns the value 300. On terminal the value that is going to appear are: 500 (first print(b) statement), 500(third print(b) statement), and 300 (third print(b) statement isnisde a() function) and 300 (fourth print(b) statement). In this case, function a() changes the value of variable "b" in the line "b=a()", because a new value is being assigned.
#Excercise 14
def Excercise_14():
def a():
print(1)
b()
print(2)
def b():
print(3)
a()
# Function a() and b() does not return anything. On terminal the value that is going to appear when function a() is being called are: 1, 3 and 2. Function b() is being called inside function a()
#Excercise 15
def Excercise_15():
def a():
print(1)
x=b()
print(x)
return 10
def b():
print(3)
return 5
y = a()
print(y)
# Function a() and b() return 10 and 5, respectivetly. On terminal the value that is going to appear when function a() is being called are: 1 (print(1) inside function a()), 3 (when calling function b() because line x=b() inside a() function), 5 (print(x)) and 10 (print(y)). Function b() is being called inside function a()
# ---------------------------------------------
# Run the function excercise to check the output here:
Excercise_15()
|
b6c600d1c0e1640b1f5918bb37f3bf0b34d5e2a6 | pymd/DataStructures | /DataStructuresPython/tree/02_MaxInBinaryTree.py | 1,650 | 3.921875 | 4 | from TreeNode import TreeNode as Node
class Tree:
def __init__(self):
self.root = None
def createNode(self, val):
node = Node()
node.setVal(val)
return node
def maxInBinaryTree (self, root):
"""
Visit each element of the tree recursively, and maintain a maximum.
Recursive visit:
Get max from LeftSubTree.
Get max from RightSubTree.
Compare lstMax, rstMax and root.
Return Max.
Time Complexity: O(n)
"""
if root == None:
return -1
lstMax = self.maxInBinaryTree (root.getLeftChild()) # Maximum val from LeftSubTree
rstMax = self.maxInBinaryTree (root.getRightChild()) # Maximum val from RightSubTree
maxVal = max(root.getVal(), lstMax, rstMax) # Max of lstMax, rstMax, and root
return maxVal
def preOrderTraversal (self, current):
if current == None:
return
self.preOrderTraversal(current.getLeftChild())
print current.getVal()," ",
self.preOrderTraversal(current.getRightChild())
def getRoot(self):
return self.root
def setRoot(self, root):
self.root = root
if __name__ == '__main__':
tree = Tree()
tree.setRoot(tree.createNode(10))
tree.getRoot().setLeftChild(tree.createNode(20))
tree.getRoot().setRightChild(tree.createNode(30))
tree.getRoot().getLeftChild().setLeftChild(tree.createNode(40))
tree.getRoot().getLeftChild().setRightChild(tree.createNode(50))
tree.getRoot().getRightChild().setLeftChild(tree.createNode(60))
tree.getRoot().getRightChild().setRightChild(tree.createNode(70))
print 'PreOrder Traversal is:'
tree.preOrderTraversal(tree.getRoot())
print ''
print 'Maximum element in the tree is:', tree.maxInBinaryTree (tree.getRoot()) |
5d46e5cd5da5caa8cad966d40f214d32cc537e0f | tjhobbs1/python | /Module6/payroll_calc.py | 1,769 | 4.40625 | 4 | """
Program: payroll_calc.py
Author: Ty Hobbs
Last date modified: 09/30/2019
The purpose of this program is to take an employees name, the number of hours they work and their rate of pay.
It will then return the total amount of pay that employee will receive.
"""
def hourly_employee_input():
# This function will get the users inputs of number of hours worked and hourly pay rate and print the paycheck amount.
# :param
# :returns: prints to the screen.
# :raises ValueError: when input is not an int
employee_name = ""
hourly_rate = 0
hours_worked = 0
# Get the employee's name.
while employee_name == "":
employee_name = input("Enter an Employee's Name: ")
# Gets the user input of the rate of pay for the employee.
while hourly_rate <= 0:
try:
hourly_rate = float(input("Enter employee's rate of pay"))
except ValueError as err: # Returns an error.
print("Enter a positive numeric value")
hourly_rate = float(input("Enter employee's rate of pay"))
# Get the user input of the number of hours worked.
while hours_worked <= 0:
try:
hours_worked = int(input("Enter the number of hours the employee worked: "))
except ValueError as err: # Returns an error.
print("Enter a positive numeric value")
hours_worked = int(input("Enter the number of hours the employee worked: "))
total_pay = hourly_rate * hours_worked
print(employee_name, "total pay is $",total_pay)
if __name__ == '__main__':
try: # check for ValueError
hourly_employee_input()
except ValueError as err:
print("Enter a positive numeric value")
hourly_employee_input()
|
2d1ec4c579c590e64ee7d37e761fe7669557d9b0 | synxelm/360video-edge-rendering | /client/client.py | 1,834 | 3.515625 | 4 | #!/usr/bin/env python
# Program:
# To set up its socket differently from the way a server does. Instead of binding to a port and listening, it uses connect() to attach the socket directly to the remote address.
# Author:
# Wen-Chih, MosQuito, Lo
# Date:
# 2017.3.11
import socket
import sys
import time
import struct
import errno
from socket import error as SocketError
# Constants
SERVER_ADDR = "140.114.77.125"
SERVER_PORT = 9487
CHUNK_SIZE = 4096
segid = 3
yaw = -120.03605833333
pitch = 0.103563888889
roll = -3.993
VIDEO = "coaster"
ORIENTATION = "coaster_user03_orientation.csv"
# End of constants
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (SERVER_ADDR, SERVER_PORT)
print >> sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
try:
# Send data
ori = (format(time.time(), '.6f'), segid, yaw, pitch, roll, VIDEO, ORIENTATION)
print >> sys.stderr, 'sending (%s, %s, %s, %s, %s, %s, %s)' % ori
mes = str(ori[0]) + "," + str(ori[1]) + "," + str(ori[2]) + "," + str(ori[3]) + "," + str(ori[4]) + "," + str(ori[5]) + "," + str(ori[6])
sock.sendall(mes)
# Receive video from server
filename = "output_" + str(ori[1]) + ".mp4"
recvfile = open(filename, "w")
print >> sys.stderr, 'downloading file...'
# recv chunks from server then save all of them
data = ""
while True:
chunk = sock.recv(CHUNK_SIZE)
data += chunk
if not chunk: break
recvfile.write(data)
recvfile.close()
print >> sys.stderr, 'finished downloading file'
except SocketError as e:
print("SocketError")
# do somthing here
finally:
print >> sys.stderr, 'closing socket'
sock.close()
|
b7cd7be832f852d66250c9e3de2b7b65465ba8f5 | 1505069266/python-study | /day9/init.py | 1,131 | 4.34375 | 4 | # 类要用大驼峰写法
class Cat:
"""定义了一个类"""
# 属性
# 初始化对象
def __init__(self,new_name,new_age):# 这个方法自动执行 除了self的参数是需要创建对象的时候输入的参数
self.name = new_name
self.age = new_age
def __str__(self): #打印对象的返回信息就这个函数返回的信息
return "名字:%s,年龄:%d"%(self.name,self.age)
# 方法
def eat(self):
print("猫在吃鱼..")
def drink(self):
print("猫在喝水..")
def introduce(self):
print("%s的年龄是:%d"%(self.name,self.age))
# 创建一个新的对象 返回对象的引用
tom = Cat("tom",40)
tom.introduce() # tom.introduce(tom)
# 获取对象的属性
lanmao = Cat("lanmao",10)
lanmao.name = "蓝猫"
lanmao.age = 10
lanmao.introduce() # tom.introduce(lanmao)
print(tom) #打印的是类的 def __str__方法的return
print(lanmao) #打印的是类的 def __str__方法的return
# 创建对象的过程:
# 1.创建一个对象
# 2.python会自动的调用__init__方法
# 3.返回这个对象的引用 |
324faecc3d04210bf75c5ac1510bda70d7d0ac0f | AbhishekKhaneja/PythonTutorial | /PythonBasics/Functions.py | 651 | 3.6875 | 4 | class abc:
num = 100
def __init__(self, a, b):
self.first = a
self.second = b
print("i am a default constructor and called automatically when a object is created")
def indian(self):
print("i am a indian nothing to do with hindu muslim")
def summation(self):
return self.first + self.second + abc.num
obj = abc(10, 20) # Syntax to create object in python no new keyword i s required like in java
obj.summation()
abc.indian(obj)
print(obj.num)
#def abhi(name):
# print("name is " + name)
#def addition (a, b):
#return a+b
#abhi("Abhishek")
#System =addition(10,20)
#print(System)
|
befe70f966dfde02516772ff7724d9883132b961 | Axel164ful/LearnPython | /26-Excepciones.py | 902 | 4.3125 | 4 | #Las excepciones son errores detectados por Python durante la ejecución del programa
Print ("hola")
try: #<--- la estructura basica de las excepciones es mediante los try except
print (x)
except: #<--- se le puede agregregar excepciones en especifico ejem TypeError= que solo funciona con
#errores de tipo de cadena.
print( "no existe" )
except ZeroDivisionError:
print ("error al dividir")
finally:
print ("me ejecuto pase lo que pase")
print ("si se pudo")
#<--- tambien podemos crear nuestra propia excepcion requiere hederar de la clase exception
class Unerror(exception):
def __init__(self, valor):
self.valorError = valor
def __str__ (self):
print (" no se puede dividir entre 1 el numero ", self.valorError)
print ("hola")
d=5
n=1
try:
if n==1
raise Unerror(d)
except Unerror:
print("se producio error")
print("adios")
|
ec4d6a4baa8299d73de537e7569ba03aef3ba382 | jasujon/Start-Python | /lession21/index.py | 2,994 | 4.6875 | 5 | #------------------------------------Intro to *args / *operator-----------------------------
# *operator
# *args
#data gather tuple
#normal function
# def total(a,b):
# return a+b
# print(total(2,3))
#output : 5
#but if we try to pass many argument
#### print(total(3,4,6))
####output : TypeError: total() takes 2 positional arguments but 3 were given
#if we try to pass many argument in my function than we can use *args or *operator
# def total(*args):
# print (args)
# #output : (1, 2, 3, 4, 5)
# print(type(args))
# #output : <class 'tuple'>
# total(1,2,3,4,5)
# * args loop function
# def all_total(*args):
# total = 0
# for num in args :
# total += num
# return total
# print(all_total(1,2,3))
#output : 6
#-----------------------------------* args with normal parameter-----------------------
# # loop with args
# def multiply_num(*args):
# multiply = 1
# for i in args:
# multiply *= i
# return(multiply)
# print(multiply_num(1,2,3))
# #output : 6
# loop with *args and normal function
# def multiply_num(num,*args):
# multiply = 1
# print(num) #output : 1
# print (args) #output : 2,3,1,5
# for i in args:
# multiply *= i
# return multiply
# print(multiply_num(1,2,3,1,5))
#output : 6
#-----------------------------------*Args as argument-----------------------
# def multiply_num(*args):
# multiply = 1
# print (args) #output : 2,3,1,5
# for i in args:
# multiply *= i
# return multiply
# num = [2,3,5]
# print(multiply_num(num))
# #output : [2, 3, 5] # args cant work because we dont use args in argument
# print(multiply_num(*num))
# #output : 30
#-----------------------------------** Kwargs(kwargs = keyword arguments)-----------------------
# **kwargs(double star argument)
# kwargs (keyword argument)
# data gather dictionary
#kwargs as a parameter
# def func(**kwargs):
# # print(kwargs)
# # print(type(kwargs))
# #output : <class 'dict'>
# for k,v in kwargs.items():
# print(f"{k} : {v}")
# func(first_name = 'Jubayed' , last_name = 'Alam')
#output : {'first_name': 'Jubayed', 'last_name': 'Alam'} #data store as a dictionary
# for output : first_name : Jubayed
# last_name : Alam
#---------------------Function with all type of parameters (mentain serial)-----------------
#normal parameter
#def func(a):
#default parameter
# def func(name = 'unknown' , age = 24):
# print(name,age)
# func()
#output : unknown 24
# 1 . parameter
# 2 . *args
# 3 . default
# 4 . **kwargs
#if u want to use all that than you must mentain serial
def func(name, *args, last_name='Alam' , **kwargs):
print(name)
print(args)
print(last_name)
print(kwargs)
func('Jubayed', 1,2,3, a = 1, b = 2)
#output :
# Jubayed
# (1, 2, 3)
# Alam
# {'a': 1, 'b': 2} |
b9c8699875f65188b373233cd95b33e21c9bfb56 | juliannepeeling/class-work | /Chapter 5/5-8.py | 232 | 3.953125 | 4 | usernames = ['admin', 'jpeeling', 'deden', 'lisah', 'paulp']
username = input("What is your username? ")
if username == 'admin':
print("Hello, admin. Would you like to see a status report?")
else:
print("Hello, " + username + "!") |
9c2b0b113d57ce3f09cac0457d29a3419e54056f | Andersirk/INF200-2019-Exersices | /src/anders_karlsen_ex/pa01/snakes_and_ladders.py | 3,192 | 3.890625 | 4 | # -*- coding: utf-8 -*-
__author__ = "Kåre Johnsen", "Anders Karlsen"
__email__ = "kajohnse@nmbu.no", "anderska@nmbu.no"
import random
import statistics as st
class Players:
def __init__(self):
self.current_position = 0
self.number_of_throws = 0
def position(self):
return self.current_position
def throw_dice_and_move(self):
self.current_position += random.randint(1, 6)
self.number_of_throws += 1
def check_ladder(self):
ladder_from = [1, 8, 36, 43, 49, 65, 68]
ladder_to = [40, 10, 52, 62, 79, 82, 85]
for start, end in zip(ladder_from, ladder_to):
if self.current_position == start:
self.current_position = end
def check_snake(self):
snake_from = [25, 33, 42, 56, 64, 74, 87]
snake_to = [5, 3, 30, 37, 27, 12, 70]
for start, end in zip(snake_from, snake_to):
if self.current_position == start:
self.current_position = end
def is_winning(self):
if self.current_position >= 90:
return True
return False
def single_game(num_players):
"""
Returns duration of single game.
Arguments
---------
num_players : int
Number of players in the game
Returns
-------
num_moves : int
Number of moves the winning player needed to reach the goal
"""
players = [Players() for _ in range(num_players)]
any_winners = False
winning_player = None
while not any_winners:
for player in players:
player.throw_dice_and_move()
player.check_ladder()
player.check_snake()
if player.is_winning():
winning_player = player
any_winners = True
return winning_player.number_of_throws
def multiple_games(num_games, num_players):
"""
Returns durations of a number of games.
Arguments
---------
num_games : int
Number of games to play
num_players : int
Number of players in the game
Returns
-------
num_moves : list
List with the number of moves needed in each game.
"""
return [single_game(num_players) for _ in range(num_games)]
def multi_game_experiment(num_games, num_players, seed):
"""
Returns durations of a number of games when playing with given seed.
Arguments
---------
num_games : int
Number of games to play
num_players : int
Number of players in the game
seed : int
Seed used to initialise the random number generator
Returns
-------
num_moves : list
List with the number of moves needed in each game.
"""
random.seed(seed)
return multiple_games(num_games, num_players)
if __name__ == "__main__":
sample_game = multi_game_experiment(100, 4, 6969)
print(f'The longest game duration is {max(sample_game)} rounds\n'
f'The shortest game duration is {min(sample_game)} rounds\n'
f'The median game duration is {st.median(sample_game):.1f} rounds\n'
f'The mean game duration is {st.mean(sample_game)} rounds, '
f'and its standard deviation is {st.stdev(sample_game):.3f}')
|
feb0870ef1fc66f49fc77d1bdf737d7644a3794b | wheejoo/PythonCodeStudy | /7주차 이분탐색,그래프/백준/랜선자르기/김휘주.py | 817 | 3.5 | 4 | # https://www.acmicpc.net/problem/1654
k,n = map(int,input().split())
line = []
for _ in range(k):
line.append(int(input()))
def solution(n, line):
left = 1
right = max(line)
while left <= right:
mid = (left + right) // 2
# print(mid)
log = 0
for l in line:
log += l // mid
# log += l - mid
# print(log)
if log >= n:
left = mid + 1
else:
right = mid - 1
return right
print(solution(n, line))
# def binary_search(i, list, start, end):
# if start > end:
# return 0
# mid = (start + end) // 2
# if i == mid:
# return 1
# elif i < mid:
# return binary_search(i, list, start, mid+1)
# else:
# return binary_search(i, list, mid-1, end)
|
01ee142df5a314a6415c8a8aa3c18a0b1f33a9dc | GuriSandal/Django_works | /Python/lcm_hcf.py | 350 | 3.78125 | 4 | num1 = int(input("Enter First Number= "))
num2 = int(input("Enter Second Number= "))
small = min([num1,num2])
large = max([num1,num2])
x = large
y = small
while(y):
x,y = y,x%y
print("H.C.F. or G.C.D.=",x)
x=large
y=small
while(True):
if((large % x == 0) and (large % y == 0)):
print("L.C.M.= ",large)
break
large += 1
|
9947d41ac9f7916fe45bfcf34832f1c3f2e44959 | hanasmarcin/leading-color-finder-service | /ClusteringAlgorithm.py | 5,567 | 3.75 | 4 | import numpy as np
POW = 3
def calculate_distance(point_a, point_b):
"""
Function calculates distance between two points
:param point_a: fist point's coordinates
:param point_b: second point's coordinates
:return: distance between two points
"""
return np.linalg.norm(point_a-point_b)
def flatten_array(array):
"""
Function transforms 3-dimensional nparray to 2-dimensional nparray
:param array: nparray with shape (h, w, 3)
:return: nparray with shape (h*w, 3)
"""
flat_array = []
for row in array:
for sample in row:
flat_array.append(sample)
return np.array(flat_array)
def calculate_distances_from_point(data, point):
"""
Function calculates distances for every sample in data to given point
:param data: nparray with shape (len, 3)
:param point: nparray with shape (3)
:return: nparray with shape (len, 1) containing distance for each sample
"""
distances = np.empty(data.shape[0])
for (i, sample) in enumerate(data):
distances[i] = calculate_distance(sample, point)
return distances
def print_full_array():
np.set_printoptions(threshold=np.inf)
class ClusteringAlgorithm:
def __init__(self, k: int, data: np.ndarray, block_points=None):
"""
Method initializes object
:param k: number of clusters, to which data will be divided
:param data: nparray with shape (h*w, 3),
containing samples (with shape (3)), that will be divided to clusters
"""
self.block_points = block_points
self.dataset = flatten_array(data)
self.points_count = self.dataset.shape[0]
self.k = k
self.centroids = np.empty((self.k, 3))
self.calculate_initial_centroids()
self.samples_per_centroid = np.zeros((self.k, 1))
def set_block_points_as_centroids(self):
distances_pow = np.ones(self.dataset.shape[0])
self.centroids[0:self.block_points.shape[0]] = self.block_points
for block_point in self.block_points:
distances = calculate_distances_from_point(self.dataset, block_point)
distances_pow *= np.float_power(distances, POW)
return distances_pow
def set_random_centroid(self, i, distances_pow, probability=None):
# if probability is None:
# probability = np.ones(distances_pow.shape)/distances_pow.shape[0]
data_indexes = range(self.points_count)
centroid_id = np.random.choice(data_indexes, p=probability)
self.centroids[i] = self.dataset[centroid_id]
distances = calculate_distances_from_point(self.dataset, self.centroids[i])
distances_pow *= np.float_power(distances, POW)
return distances_pow
def calculate_initial_centroids(self):
"""
Method calculates k centroids (clusters "origins")
:return: calculated clusters, nparray with shape(k, 3)
"""
distances_pow = np.ones(self.dataset.shape[0])
if self.block_points is not None:
distances_pow = self.set_block_points_as_centroids()
else:
distances_pow = self.set_random_centroid(0, distances_pow)
probability_for_samples = distances_pow/sum(distances_pow)
# find rest of centroids
for i in range(self.block_points.shape[0] if self.block_points is not None else 1, self.k):
distances_pow = self.set_random_centroid(i, distances_pow, probability=probability_for_samples)
probability_for_samples = distances_pow/sum(distances_pow)
return self.centroids
def calculate_distances_for_data(self):
distances = np.empty((self.k, self.points_count))
for i, centroid in enumerate(self.centroids):
distances[i] = calculate_distances_from_point(self.dataset, centroid)
return distances
def calculate_clusters(self):
distances = self.calculate_distances_for_data()
cluster_ids = np.argmin(distances, axis=0)
self.centroids = self.calculate_centroids_for_clusters_samples(cluster_ids)
return cluster_ids
def calculate_final_clusters(self):
cluster_ids = np.empty(self.points_count)
iteration = 0
while True:
iteration += 1
new_cluster_ids = self.calculate_clusters()
if np.array_equal(cluster_ids, new_cluster_ids) or iteration >= 5:
break
cluster_ids = new_cluster_ids
return self.centroids, self.samples_per_centroid
def calculate_centroids_for_clusters_samples(self, cluster_ids):
"""
Method calculates new centroids for given samples' distances
from existing centroids and their assignment to them
:param cluster_ids: nparray with shape (h*w, 1)
:return:
"""
new_centroids = np.zeros((self.k, 3))
samples_per_centroid = np.zeros((self.k, 1))
for sample_id, cluster_id in enumerate(cluster_ids):
new_centroids[cluster_id] = np.add(new_centroids[cluster_id], self.dataset[sample_id])
samples_per_centroid[cluster_id] += 1
denominator = np.ones(new_centroids.shape)
denominator *= samples_per_centroid
self.samples_per_centroid = samples_per_centroid.flatten()
with np.errstate(invalid='ignore'):
new_centroids = np.divide(new_centroids, denominator)
if self.block_points is not None:
new_centroids[0:self.block_points.shape[0]] = self.block_points
return new_centroids
|
2695819330b303df541b3d74cce1ebcbc8cf7dff | prajjwalkumar17/DSA_Problems- | /dp/Dice_Throw.py | 3,343 | 4.03125 | 4 | """
Author: Akash Kumar Bhagat (akay_99)
Dice Throw Problem : Given n dice each with m faces, numbered
from 1 to m, find the number of ways to get sum X.
X is the summation of values on each face when all
the dice are thrown.
Purpose: Return the number of ways you can get a sum equal to K
by throwing a M faced dice for N times.
Method: Dynamic Programing
Intution:The Naive approach is to find all possible combinations from N dice
and keep counting the if the desired sum is achieved
Sum(m, n, X)=Finding Sum (X - 1) from (n - 1) dice plus 1 from nth dice
+ Finding Sum (X - 2) from (n - 1) dice plus 2 from nth dice
+ Finding Sum (X - 3) from (n - 1) dice plus 3 from nth dice
...................................................
...................................................
...................................................
+ Finding Sum (X - m) from (n - 1) dice plus m from nth dice
We can use Dynamic Programing to solve this problem efficiently because
this problem contains many overlaping Sub-problems which need to be
calculated again and again. We can use Dynamic Programing to store the
result of the previous sub-problems.
Time Complexity: O(N*K)
Space Complexity: O(N*K)
Argument: 3 Integers (M, N and K)
Return : Integer (Number of ways)
Reference: https://www.geeksforgeeks.org/dice-throw-dp-30/
"""
def Dice_Throw(n, m, k):
# DP table to store the results of all possible sub-problems in a matrix
# Here DP[i][j] denoted the Number of ways to get the sum j with i throws
DP = [[0] * (k + 1) for i in range(n + 1)]
# By convention, the 0th index of the matrix will not be used and
# the value at DP[0][0] must be 1
DP[0][0] = 1
# Iterate through 1 to n dice trows
for i in range(1, n + 1):
# For each dice thrown, re-calculate the number of ways to get the
# target sum j from i throws
for j in range(1, k + 1):
DP[i][j] = DP[i][j - 1] + DP[i - 1][j - 1]
if j - m - 1 >= 0:
DP[i][j] -= DP[i - 1][j - m - 1]
# Return the answer i.e. the last cell value of the DP table
return DP[-1][-1]
# ------------------------------- DRIVER CODE ------------------------------
if __name__ == "__main__":
# User input for the Number of dice, Number of faces and Target Sum
n, m = map(
int, input("Enter the Number of dice and number of faces: ").split())
k = int(input("Enter the Target Sum: "))
# we call the Dice_Throw() function with provided arguments to get the
# answer
ans = Dice_Throw(n, m, k)
print("Total Number of Ways to get the target sum= ", ans)
"""
Sample Input / Output
Enter the Number of dice and number of faces: 1 6
Enter the Target Sum: 5
Total Number of Ways to get the target sum= 1
Explanation: (5)
Enter the Number of dice and number of faces: 2 6
Enter the Target Sum: 5
Total Number of Ways to get the target sum= 4
Explanation: (1, 4), (2, 3), (3, 2) and (4, 1)
Enter the Number of dice and number of faces: 4 6
Enter the Target Sum: 5
Total Number of Ways to get the target sum= 4
Explanation: (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1) and (2, 1, 1, 1)
"""
|
40bfd6f68f59233ae0791321afc79b251e487db3 | chirag1992m/geeky | /HackerRank/ProjectEuler/euler004.py | 842 | 3.890625 | 4 | #!/bin/python3
'''
Largest Palindrome Product
https://www.hackerrank.com/contests/projecteuler/challenges/euler004
'''
import sys
'''
Pre-calculate all the palindromes
time complexity: O(899 + 898 + 897... + 1)
The list only contains around 600 unique members,
which is not to hard to search for with a
simple linear search
'''
def is_palindrome(num):
if str(num)[::-1] == str(num):
return True
return False
palindromes = []
for i in range(101, 1000):
for k in range(i, 1000):
x = i*k
if is_palindrome(x):
palindromes.append(x)
palindromes.sort()
size = len(palindromes)
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
for palin in palindromes[::-1]:
if n > palin:
print(palin)
break |
c49939de6a0b7808ff4298c84e263ec95c6dfa96 | tharani247/PFSD-Python-Programs | /Module 1/Program-60.py | 394 | 4.40625 | 4 | # 60.python program to demonstrate polymorphism(Method Overloading)
class shape:
def area(s,a=None,b=None):
if a!=None and b!=None:
print("Area:",a*b)
elif a!=None:##special literal None
print("Area:",a*a)
else:
print("Area:",0)
s=shape()
s.area()
s.area(5)
s.area(4, 10)
'''output
Area: 0
Area: 25
Area: 40'''
|
757c8a6da36b360d3c1d08032d024ab2cfd0d276 | longfight123/16-CoffeeMachineProject | /main.py | 3,559 | 3.875 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
RESOURCES = {
"water": 300,
"milk": 200,
"coffee": 100,
"profit": 0
}
def check_resources_sufficient(drink_type):
if drink_type == 'espresso':
if MENU[drink_type]["ingredients"]["water"] > RESOURCES["water"]:
print('Sorry there is not enough water.')
return False
if MENU[drink_type]["ingredients"]["coffee"] > RESOURCES["coffee"]:
print('Sorry there is not enough coffee.')
return False
if drink_type in ['cappuccino', 'latte']:
if MENU[drink_type]["ingredients"]["water"] > RESOURCES["water"]:
print('Sorry there is not enough water.')
return False
if MENU[drink_type]["ingredients"]["coffee"] > RESOURCES["coffee"]:
print('Sorry there is not enough coffee.')
return False
if MENU[drink_type]["ingredients"]["milk"] > RESOURCES['milk']:
print('Sorry there is not enough milk.')
return False
return True
def check_coins_sufficient(quarters_inserted, dimes_inserted, nickels_inserted, pennies_inserted, drink_type):
total_coins_inserted = quarters_inserted + dimes_inserted + nickels_inserted + pennies_inserted
if total_coins_inserted >= MENU[drink_type]['cost']:
change = round(total_coins_inserted - MENU[drink_type]['cost'], 2)
print(f'Here is your change: {change}$')
return True
else:
print('Sorry that is not enough money. Money refunded.')
return False
def make_a_drink():
user_drink = input('Hello, what would you like? (espresso/latte/cappuccino)')
if user_drink == 'report':
print(f'Water: {RESOURCES["water"]}ml\nMilk: {RESOURCES["milk"]}ml\nCoffee {RESOURCES["coffee"]}ml\n'
f'Money {RESOURCES["profit"]}$')
elif user_drink == 'off':
return
elif user_drink in ['espresso', 'latte', 'cappuccino']:
if not check_resources_sufficient(user_drink):
make_a_drink()
print('Please insert coins:')
quarters = int(input('Quarters:'))*0.25
dimes = int(input('Dimes:'))*0.1
nickels = int(input('Nickels:'))*0.05
pennies = int(input('Pennies:'))*0.01
if not check_coins_sufficient(quarters_inserted=quarters, dimes_inserted=dimes,
nickels_inserted=nickels, pennies_inserted=pennies, drink_type=user_drink):
make_a_drink()
if user_drink == 'espresso':
RESOURCES['water'] -= MENU[user_drink]['ingredients']['water']
RESOURCES['coffee'] -= MENU[user_drink]['ingredients']['coffee']
elif user_drink in ['latte', 'cappuccino']:
RESOURCES['water'] -= MENU[user_drink]['ingredients']['water']
RESOURCES['coffee'] -= MENU[user_drink]['ingredients']['coffee']
RESOURCES['milk'] -= MENU[user_drink]['ingredients']['milk']
RESOURCES['profit'] += MENU[user_drink]['cost']
print(f'Here is your drink: {user_drink}')
else:
print('That is not a valid drink.')
make_a_drink()
make_a_drink()
|
9415ad86d1d84d28d09f9475a576cfac9380f481 | amanpate531/undergraduate_portfolio | /Year 4/CSCI-A 310/Labs/LinkedList.py | 1,932 | 4.125 | 4 | # Aman Patel
# CSCI-A 310
# January 31, 2021
class Empty:
def __init__(self):
pass
def cons(self, item):
return LinkedList(item)
def length(self):
return 0
def isEmpty(self):
return True
def append(self, lst):
return lst
def __str__(self):
return "Empty"
class LinkedList:
def __init__(self, elem):
self.first = elem
self.rest = Empty()
def get_rest(self):
return self.rest
def get_first(self):
return self.first
def cons(self, item):
a = LinkedList(item)
a.rest = self
return a
def length(self):
return self.rest.length() + 1
def append(self, lst):
if lst.isEmpty():
return self
else:
a = self.get_rest().append(lst)
return a.cons(self.get_first())
def isEmpty(self):
return False
def __str__(self):
return str(self.first) + " " + str(self.rest)
def main():
a = Empty()
print( "Empty list: " + str(a) )
print( "Is the list empty at this stage? Answer: " + str(a.isEmpty()) )
print( "How long is the list at this stage? Answer: " + str(a.length()) )
a = a.cons(3)
print( "Adding 3 list becomes: " + str(a) )
print( "Is the list empty at this stage? Answer: " + str(a.isEmpty()) )
a = a.cons(5)
print( "Adding 5 list becomes: " + str(a) )
a = a.cons(1)
print( "Adding 1 list becomes: " + str(a) )
print( "How long is the list at this stage? Answer: " + str(a.length()) )
a = a.get_rest().get_rest().cons(1)
print( "Taking out the 5 the list becomes: " + str(a) )
print( "Is the list empty at this stage? Answer: " + str(a.isEmpty()) )
b = Empty()
b = b.cons(9)
c = a.append(b)
print( str(a) + " append " + str(b) + " produces " + str(c) )
if __name__=="__main__":
main()
|
a65b0020802d2d0d23c56922705e7e75a7209312 | cristianjs19/codefights-solutions-Python | /The Core/54 - isCase-InsensitivePalindrome?/isCase-InsensitivePalindrome.py | 176 | 3.5 | 4 | def isCaseInsensitivePalindrome(inputString):
reverse = inputString[::-1]
if inputString.lower() == reverse.lower():
return True
else:
return False |
77fca5d1a9c12910075eb292a65c799222399372 | zxl123129/Business-card-management | /cards_tools.py | 3,819 | 3.8125 | 4 | #记录所有的名片字典
card_list =[]
def show_menu():
"""显示菜单"""
print("*"*50)
print("欢迎使用【名片管理系统】v1.0")
print("")
print("1.新增名片")
print("2.显示全部")
print("3.搜索名片")
print("")
print("0.退出系统")
print("*"*50)
def new_card():
"""新增名片"""
print("-"*50)
print("新增名片")
#1.提示用户输入名片信息
name_str = input("请输入姓名:")
phone_str = input("请输入电话:")
qq_str = input("请输入qq:")
emile_str = input("请输入用户的邮箱:")
#2.使用用户输入的名片信息建立一个名片字典
card_dict = {"name":name_str,
"phone":phone_str,
"qq":qq_str,
"emile":emile_str}
#3.将名片字段添加到列表中
card_list.append(card_dict)
print(card_list)
#4.提示用户输入成功
print("添加%s的名片成功!"%name_str)
def show_all():
"""显示所有名片"""
print("-" * 50)
print("显示所有名片")
#判断是否存在名片记录,如果没有,提示用户并且返回
if len(card_list)==0:
print("当前没有任何名片记录,请使用新增功能增加名片!")
return
#打印表头
for name in ["姓名","电话","QQ","邮箱"]:
print(name,end="\t\t")
print("")
#打印分割线
print("=" * 50)
#遍历名片列表依次输出字典信息
for card_dict in card_list:
print("%s\t\t%s\t\t%s\t\t%s"%(card_dict["name"],
card_dict["phone"],
card_dict["qq"],
card_dict["emile"]))
def search_card():
""""搜索名片"""
print("-" * 50)
print("搜索名片")
#1.提示用户输入要搜索的姓名
find_name = input("请输入要搜索的姓名:")
for card_dict in card_list:
if card_dict["name"]==find_name:
print("姓名\t\t电话\t\tQQ\t\t邮箱")
print("="*50)
print("%s\t\t%s\t\t%s\t\t%s" % (card_dict["name"],
card_dict["phone"],
card_dict["qq"],
card_dict["emile"]))
deal_card(card_dict)
break
else:
print("抱歉,没有找到%s"% find_name)
#2.
def deal_card(find_card):
"""
处理查找到的名片
:param find_card:查找到的名片
"""
action_str = input("请选择需要执行的操作"
" 1修改 2删除 0返回上级菜单")
if action_str=="1":
find_card["name"]=input_card_info(find_card["name"],"请输入修改的姓名:")
find_card["phone"]=input_card_info(find_card["phone"],"请输入修改的电话:")
find_card["qq"]=input_card_info(find_card["qq"],"请输入修改的qq:")
find_card["emile"]=input_card_info(find_card["emile"],"请输入修改的emile:")
print("修改名片")
elif action_str=="2":
card_list.remove(find_card)
print("删除名片")
def input_card_info(dict_value,tip_message):
"""输入名片信息
:param dict_value: 字典中原有的值
:param tip_message:输入提示的文字
:return:如果用户输入了内容,就返还内容,没有输入内容,输出字典原有的值
"""
#1.提示用户输入内容
result_str = input(tip_message)
#2.针对用户的输入进行判断,如果用户输入了内容,直接返还结果
if len(result_str)>0:
return result_str
else:
return dict_value
#3.如果用户没有输入内容,返还字段中原有的值 |
96973203f93a28bdfbdd4951e7751613ab691d6f | skymoonfp/python_learning | /python_project/test/test.py | 5,464 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding:UTF-8 -*-
print("3")
# # 查看当前文件路径
# import os
# os.system("cd")
#
# # 显示当前文件夹信息
# import os
# os.system("dir")
#
# # 保存当前文件路径
# import os
# path = os.popen("cd").read()
# print(path)
#
# # 查看模块详细信息
# help("os")
#
# # 查看模块内方法
# print(dir(os))
# # 文件读写方式
# encode_test = open("E:\\DataAnalysis\\python_project\\encode_test.txt", "w")
# encode_test.write("柏拉12ab、_%图、苏格拉底、赫拉克利特\n")
# encode_test.write("亚里士多德、笛卡尔")
# encode_test.close()
#
# encode_test = open("encode_test.txt", "r")
# for line in encode_test.readlines():
# list01 = line.strip().split("、")
# # for element in list01:
# # print(element)
# for i in range(len(list01)):
# print(list01[i])
# encode_test.close()
#
# # 文件属性和方法
# help(encode_test)
# encode_test = open("encode_test.txt", "w")
# encode_test = open("encode_test.txt", "a")
# encode_test = open("encode_test.txt", "r")
# encode_test.close()
# encode_test.mode
# encode_test.name
# encode_test.read(25)
# encode_test.readline(25)
# encode_test.readlines(25)
# encode_test.next() # 过气
# next(encode_test)
# encode_test.tell()
# encode_test.seek(4)
# encode_test.write("李斯")
# encode_test.truncate(12)
# # 始终从头开始截取;
# # "w"(在清空之后进行截取,结果始终为空),"a"(在原文本上进行截取);
# # 截取数为字节数;
# # txt文本用gbk编码,每个汉字占两个字节,每个数字或英文字母占一个字节,每个全角标点占两个字节,每个半角标点占一个字节
# print(encode_test)
# help(encode_test.readlines)
# list
list01 = ["ad", "分配", "1", "7**"]
help(list01)
list01.insert(2, "a+b=")
list01.index("a")
help(list)
# -----------同步变化---------------
list01 = ["ad", "分配", "1", "7**"]
list02 = list01
list01[0] = "AD"
print(list01, list02)
# -----------相互独立---------------
str01 = "abd"
str02 = str01
str01 = str01[1:]
print(str01, str02)
# -----------相互独立---------------
list01 = ["ad", "分配", "1", "7**"]
list02 = list01
list01 = list01[1:]
print(list01, list02)
# -----------同步变化---------------
list01 = ["ad", "分配", "1", "7**"]
list02 = list01
list01.insert(2, "a+b=")
print(list01, list02)
# -----------同步变化---------------
list01 = ["ad", "分配", "1", "7**"]
list02 = list01
list01.append("a+b=c")
print(list01, list02)
# ---------------------------------
list01 = ["1", ["2", "3"], ["2", "3"]]
list02 = list01
list03 = list01.copy()
list04 = []
for i in range(3):
list04.append(list01[i].copy())
print(list01, list02, list03, list04)
list01.insert(1, ["2"]) # 1
list01.pop() # 2
list01.replace(["2", "3"], ["4"]) # 3
list01[1] = ["4"] # 4
list01[1].append("5") # 5
# ---------------------------------
list01 = [["1"], ["2", "3"], ["2", "3"]]
list04 = []
list05 = []
for i in range(3):
list04.append(list01[i].copy())
for i in range(len(list04)):
if list04[i] not in list05:
list05.append(list04[i])
else:
pass
print(list01)
print(list04)
print(list05)
# ---------------------------------
list01 = [["1"], ["2", "3"], ["2", "3"]]
list04 = []
list05 = []
for i in range(3):
list04.append(list01[i].copy())
for i in range(len(list04)):
if list04[i] not in list05:
list05.append(list04[i])
else:
pass
list01 = [["1", "2"], ["2", "3"], ["2", "3"]]
print(list01)
print(list04)
print(list05)
# ---------------------------------
list01 = [["1"], ["2", "3"], ["2", "3"]]
list04 = []
list05 = []
for i in range(3):
list04.append(list01[i].copy())
for i in range(len(list04)):
if list04[i] not in list05:
list05.append(list04[i])
else:
pass
list01 = [["1"], ["2", "3", "4"], ["2", "3"]]
print(list01)
print(list04)
print(list05)
# ---------------------------------
list01 = [["1"], ["2", "3"], ["2", "3"]]
list04 = []
list05 = []
for i in range(3):
list04.append(list01[i].copy())
for i in range(len(list04)):
if list04[i] not in list05:
list05.append(list04[i])
else:
pass
list01[1] = ["2", "3", "4"]
print(list01)
print(list04)
print(list05)
# ---------------------------------
list01 = []
list01.append(["1"])
a = []
a.append("2")
a.append("3")
list01.append(a.copy())
a.pop()
a.pop()
a.append("2")
a.append("3")
list01.append(a.copy())
list05 = []
for i in range(len(list01)):
if list01[i] not in list05:
list05.append(list01[i])
else:
pass
print(list01)
print(list05)
# ---------------------------------
list01 = []
list01.append(["1"])
a = []
a.append("2")
a.append("3")
list01.append(a.copy())
a.pop()
a.pop()
a.append("2")
a.append("3")
list01.append(a.copy())
list05 = []
for i in range(len(list01)):
list01[i].append("0")
if list01[i] not in list05:
list05.append(list01[i])
else:
pass
print(list01)
print(list05)
# ---------------------------------
list01 = []
list01.append(["1"])
a = []
a.append("2")
a.append("3")
list01.append(a.copy())
a.pop()
a.pop()
a.append("2")
a.append("3")
list01.append(a.copy())
list05 = []
for i in range(len(list01)):
list01[i].append("0")
if list01[i] not in list05:
list05.append(list01[i].copy())
else:
pass
print(list01)
print(list05)
def back():
a = input("input")
b = input("input")
return a, b
print(back())
|
88c67c79a374572d89ca01d06819fa3babda562f | SamyT-code/Python-Assignments | /a4_Q3_300184721.py | 848 | 4.125 | 4 | # Family name: Samy Touabi
# Student number: 300184721
# Course: ITI 1120 C
# Assignment Number 4 Question 3
# year 2020
raw_input = input("Please enter a list of integers separated by spaces: ").strip().split()
n = []
for i in raw_input:
n.append(float(i))
def longest_run(n):
'''(list of numbers) -> int
Preconditions: the list is made up of numbers
Returns the lenght of the longest run of the list
'''
counter = 1
new_counter = 1
a = len(n)
if a==0 : # If list is empty
return 0
for i in range(a-1):
if n[i] == n[i+1]:
counter = counter + 1
elif n[i] != n[i+1]:
counter = 1 #restart the counter
if counter > new_counter:
new_counter = counter
return new_counter
print(longest_run(n))
|
76b9873a232c5c9eb13d24bba3612ba73b729a9d | RoyalBosS-Ayush/IndianFlag-Turtle | /IndianFlag.py | 730 | 3.59375 | 4 | from turtle import *
def draw_rect(x,y,l,b,color):
goto(x,y)
fillcolor(color)
begin_fill()
pendown()
for _ in range(2):
forward(b)
left(90)
forward(l)
left(90)
end_fill()
penup()
def draw_chakra(x,y,r,color):
goto(x,y-r)
pencolor(color)
pendown()
circle(r)
for _ in range(24):
penup()
goto(x,y)
pendown()
forward(r)
right(15)
# speed(0)
penup()
draw_rect(-170,-260,30,160,'brown')
draw_rect(-130,-230,30,80,'brown')
draw_rect(-100,-200,400,20,'brown')
draw_rect(-80,150,40,250,'#ff9933')
draw_rect(-80,110,40,250,'white')
draw_rect(-80,70,40,250,'green')
draw_chakra(45,130,15,'blue')
hideturtle()
done() |
a48d59e04015faae08ec0f7aa38305af525cdae6 | RwJr89/PythonClass | /bounce.py | 355 | 4.15625 | 4 | height = float(input("Enter the height:"))
bouncy_index = float(input("Enter the bounciness index:"))
bounces = int(input("Enter the number of bounces:"))
distance = 0
while bounces > 0:
distance = distance + height
height = height * bouncy_index
distance = distance + height
bounces -= 1
print("The distance traveled is:", distance)
|
9a9e7d12157da0be07fbaea24147f84309aeddca | Zirmaxer/Python_learning | /Prometeus/tmp.py | 327 | 4.21875 | 4 | def MyInputInteger ():
while True:
try:
number_of_words = int(input('Please, enter number of words in the sentence:'))
return number_of_words
except:
print('Not an integer number. Try again!')
continue
return number_of_words
a = MyInputInteger()
print(a) |
5a3df3aef1cfede1dfeb6c52f449e1ae54027218 | fallaciousreasoning/KDD2014 | /smalleriser.py | 685 | 3.53125 | 4 | """Just uses the first 300 rows for testing"""
def smallerise(filename, lines_count = 6000):
"""Creates a small version of different files"""
lines = []
with open(filename, 'r', errors='ignore') as f:
for i in range(lines_count):
try:
lines.append(f.readline())
except:
print('uh oh, coudln\'t read line',i,'of', filename)
parts = filename.split('.')
small_filename = parts[0] + '_small.' + parts[1]
with open(small_filename, 'w') as f:
for line in lines:
f.write(line)
filenames = [
'donations.csv',
'essays.csv',
'projects.csv',
'resources.csv'
]
for filename in filenames:
try:
smallerise(filename)
except:
print('couldn\'t read', filename) |
d36c3b6010b3121293b0eb30c806bf9244b49e32 | alikemalcelik42/Fibonacci | /main.py | 263 | 4.125 | 4 | # Fibonacci Serisi
def Fibonacci(first, second, max):
if first + second > max:
pass
else:
print("{} - {}".format(second, first + second))
Fibonacci(second, first + second, max)
max = int(input("Enter Max: "))
Fibonacci(1, 2, max) |
ab601b35098b41ee81f116bc1866a538883f17a2 | SaiSanthoshikiran/python-programs | /lucky number.py | 432 | 3.640625 | 4 | #"printing the num if no.of occurences and the num is same --lucky num ,in case 2 or more possible outcomes printing the largest val"
def lucky(arr):
c={}
for i in arr:
c[i]=c.get(i,0)+1
print(c)
for i in sorted(set(arr),reverse=True):
if i==c[i]:
return i
return -1
arr=list(map(int,input().split()))
print(lucky(arr))
OUTPUT:
1 2 2 3 4
{1: 1, 2: 2, 3: 1, 4: 1}
2
|
eb09f9c962ac361ea78af8714aa18d8414c0d631 | shobhit-nigam/qti_panda | /day5/adv_funcs/6.py | 174 | 3.71875 | 4 | listx = ["joey", "does'nt", "share", "food"]
print(list(enumerate(listx)))
print(list(enumerate(listx, start=6)))
enum = (enumerate(listx))
print(type(enum))
print(enum)
|
aeae73a356a8c3e44d1d1f3ed76160236ca5c8e7 | LucasVanni/Curso_Python | /Exercícios/ex015.py | 251 | 3.546875 | 4 | dias = int(input('Informe a quantia de dias que o carro foi alugado: '))
kmR = float(input('Informe quantos Kilometros foram percorridos pelo carro: '))
pago = (dias * 60) + (kmR * 0.15)
print('O total a pagar é de R$ {:.2f}'.format(pago))
|
6393aa3091b64375bdc51e691807eab7dda4681b | abhishekbansal815/TicTacToe | /main.py | 10,082 | 3.640625 | 4 | # This is a game called tic tac toe
# you can play with friend or AI
# add score,reset and undo button
import math
import random
import pygame
import time
pygame.init()
pygame.display.set_caption("Tic Tac Toe")
pygame.display.set_icon(pygame.image.load("icon.png"))
win = pygame.display.set_mode((400, 500))
background = pygame.image.load("background.jpg")
board = pygame.image.load("board.png")
cross = pygame.image.load("cross.png")
nought = pygame.image.load("nought.png")
Clock = pygame.time.Clock()
fps = 10
black = (0, 0, 0)
white = (255, 255, 255)
run = True
level = -1
grid = [[" " for x in range(3)] for y in range(3)]
X = "X"
O = "O"
turn = random.choice([X, O])
def opponent(turn):
if turn == X:
return O
return X
def winCheck(x, y):
for i in range(3):
if grid[x][i] != turn:
break
else:
return True
for i in range(3):
if grid[i][y] != turn:
break
else:
return True
if x == y:
for i in range(3):
if grid[i][i] != turn:
break
else:
return True
if x + y == 2:
for i in range(3):
if grid[2-i][i] != turn:
break
else:
return True
return False
def isTie():
for i in range(3):
for j in range(3):
if grid[i][j] == " ":
return False
else:
return True
def endText(msg):
global run, grid, turn
for i in range(3):
for j in range(3):
grid[i][j] = " "
turn = opponent(turn)
time.sleep(0.25)
win.blit(background, (0, 0))
text = pygame.font.SysFont(
None, 100).render(msg, True, white)
win.blit(text, [200 - 20*len(msg), 130])
pygame.draw.rect(win, white, (60, 250, 300, 60))
text = pygame.font.SysFont(
None, 50).render("Play Again!", True, black)
win.blit(text, [85, 260])
pygame.draw.rect(win, white, (60, 350, 300, 60))
text = pygame.font.SysFont(
None, 50).render("Main Menu", True, black)
win.blit(text, [85, 360])
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
if 60 <= mx <= 360 and 250 <= my <= 310:
play()
elif 60 <= mx <= 360 and 350 <= my <= 410:
main()
pygame.display.update()
Clock.tick(fps)
def isWinner(turn):
for i in range(3):
for j in range(3):
if grid[i][j] != turn:
break
else:
return True
for j in range(3):
if grid[j][i] != turn:
break
else:
return True
for i in range(3):
if grid[i][i] != turn:
break
else:
return True
for i in range(3):
if grid[i][2 - i] != turn:
break
else:
return True
return False
def minimaxPro(alpha, beta, isMaximizing):
if isWinner(X):
return 1
if isWinner(O):
return - 1
if isTie():
return 0
if isMaximizing:
bestScore = -math.inf
for i in range(3):
for j in range(3):
if grid[i][j] == " ":
grid[i][j] = X
score = minimaxPro(alpha, beta, False)
grid[i][j] = " "
bestScore = max(score, bestScore)
alpha = max(alpha, score)
if beta <= alpha:
break
return bestScore
else:
bestScore = math.inf
for i in range(3):
for j in range(3):
if grid[i][j] == " ":
grid[i][j] = O
score = minimaxPro(alpha, beta, True)
grid[i][j] = " "
bestScore = min(score, bestScore)
beta = min(beta, score)
if beta <= alpha:
break
return bestScore
def AI():
global turn, grid
if level == 3 or random.choice([0, 1, level, level == 2]):
bestScore = -math.inf
for i in range(3):
for j in range(3):
if grid[i][j] == " ":
grid[i][j] = X
score = minimaxPro(-math.inf, math.inf, False)
grid[i][j] = " "
if score > bestScore:
bestScore = score
x, y = i, j
else:
while True:
i, j = random.randint(0, 2), random.randint(0, 2)
if grid[i][j] == " ":
x, y = i, j
break
if x == 0:
xcord = 40
elif x == 1:
xcord = 160
elif x == 2:
xcord = 275
if y == 0:
ycord = 40
elif y == 1:
ycord = 160
elif y == 2:
ycord = 275
win.blit(cross, (xcord, ycord))
pygame.display.update()
grid[x][y] = X
if winCheck(x, y):
endText("AI WIN!")
elif isTie():
endText("TIE!")
else:
turn = O
def play():
global run, grid, turn
win.blit(background, (0, 0))
win.blit(board, (10, 10))
if level != -1 and turn == X:
AI()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
x, y = -1, -1
xcord, ycord = 0, 0
if 35 < mx < 130:
x, xcord = 0, 40
elif 155 < mx < 250:
x, xcord = 1, 160
elif 270 < mx < 365:
x, xcord = 2, 275
if 35 < my < 130:
y, ycord = 0, 40
elif 155 < my < 250:
y, ycord = 1, 160
elif 270 < my < 365:
y, ycord = 2, 275
if x != -1 and y != -1:
if grid[x][y] == " ":
if turn == X:
win.blit(cross, (xcord, ycord))
else:
win.blit(nought, (xcord, ycord))
pygame.display.update()
grid[x][y] = turn
if winCheck(x, y):
if level != -1:
endText("YOU WIN!")
else:
endText(turn+" WIN!")
elif isTie():
endText("TIE!")
else:
turn = opponent(turn)
if level != -1:
AI()
pygame.display.update()
Clock.tick(fps)
def difficulty():
global run, level
win.blit(background, (0, 0))
text = pygame.font.SysFont(
None, 60).render("Select Difficulty!", True, white)
win.blit(text, [40, 60])
pygame.draw.rect(win, white, (60, 130, 300, 60))
text = pygame.font.SysFont(
None, 50).render("Easy", True, black)
win.blit(text, [85, 140])
pygame.draw.rect(win, white, (60, 200, 300, 60))
text = pygame.font.SysFont(
None, 50).render("Medium", True, black)
win.blit(text, [85, 210])
pygame.draw.rect(win, white, (60, 270, 300, 60))
text = pygame.font.SysFont(
None, 50).render("Hard", True, black)
win.blit(text, [85, 280])
pygame.draw.rect(win, white, (60, 340, 300, 60))
text = pygame.font.SysFont(
None, 50).render("Impossible", True, black)
win.blit(text, [85, 350])
pygame.draw.rect(win, white, (60, 410, 300, 60))
text = pygame.font.SysFont(
None, 50).render("Main Menu", True, black)
win.blit(text, [85, 420])
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
if 60 <= mx <= 360 and 130 <= my <= 190:
level = 0
play()
elif 60 <= mx <= 360 and 200 <= my <= 260:
level = 1
play()
elif 60 <= mx <= 360 and 270 <= my <= 330:
level = 2
play()
elif 60 <= mx <= 360 and 340 <= my <= 400:
level = 3
play()
elif 60 <= mx <= 360 and 410 <= my <= 460:
main()
pygame.display.update()
Clock.tick(fps)
def main():
global run
win.blit(background, (0, 0))
text = pygame.font.SysFont(
None, 70).render("TIC TAC TOE!", True, white)
win.blit(text, [50, 80])
pygame.draw.rect(win, white, (60, 200, 300, 60))
text = pygame.font.SysFont(
None, 50).render("YOU VS FRIEND", True, black)
win.blit(text, [75, 210])
pygame.draw.rect(win, white, (60, 300, 300, 60))
text = pygame.font.SysFont(
None, 50).render("YOU VS AI", True, black)
win.blit(text, [85, 310])
pygame.draw.rect(win, white, (60, 400, 300, 60))
text = pygame.font.SysFont(
None, 50).render("EXIT!", True, black)
win.blit(text, [85, 410])
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
if 60 <= mx <= 360 and 200 <= my <= 260:
play()
elif 60 <= mx <= 360 and 300 <= my <= 360:
difficulty()
elif 60 <= mx <= 360 and 400 <= my <= 460:
exit()
pygame.display.update()
Clock.tick(fps)
main()
|
85f3ee7ef1d9713dafcca2fe45c409f2811921e6 | RaniaMahmoud/SW_D_Python | /Sheet4/S4/P10.py | 128 | 3.53125 | 4 | list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
l=[x for x in list1 if x != ""]
print (l)
r= list(filter(None,list1))
print(r) |
95ddcb895f50995da23a5c6c74a816352dda5efc | zdyxry/LeetCode | /dynamic_programming/1546_maximum_number_of_non_overlapping_subarrays_with_sum_equals_target/1546_maximum_number_of_non_overlapping_subarrays_with_sum_equals_target.py | 491 | 3.640625 | 4 | from typing import List
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
s = {0}
cur_sum = 0
ans = 0
for num in nums:
cur_sum += num
if cur_sum - target in s:
s = {0}
cur_sum = 0
ans += 1
else:
s.add(cur_sum)
return ans
nums = [1,1,1,1,1]
target = 2
res = Solution().maxNonOverlapping(nums, target)
print(res) |
66876f6b661e802a6b98f0352bbf0cdfb21105ab | schulzsebastian/python_firststeps | /playlista.py | 733 | 3.5 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Tworzenie playlisty z tagu na Wykopie
"""
import urllib
import re
def stworz_playliste(tag):
url = 'http://www.wykop.pl/tag/' + tag
html = urllib.urlopen(url).read()
links = re.findall('href="https://www.youtube.com/watch\?v=([a-zA-Z0-9]+)"', html)
powtorki = []
lista_utworow = ""
for link in links:
if link in powtorki: continue
powtorki.append(link)
lista_utworow = lista_utworow + link + ","
playlista = 'http://www.youtube.com/watch_videos?video_ids=' + lista_utworow
return playlista
if __name__ == '__main__':
tag = raw_input('Podaj nazwe tagu do stworzenia playlisty z Wykopu: ')
print stworz_playliste(tag)
|
1341c126165519be7d49175962e14de9a96219d0 | kartikeychoudhary/competitive_programming | /hackerrank/problem_solving/strings/funny_string.py | 650 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the funnyString function below.
def funnyString(s):
rs = s[::-1]
flag = True
print(s, rs)
r1 = []
r2 = []
for x in range(len(s)-1):
r1.append(abs(ord(s[x])-ord(s[x+1])))
r2.append(abs(ord(rs[x])-ord(rs[x+1])))
if r1 == r2:
return "Funny"
else:
return "Not Funny"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
s = input()
result = funnyString(s)
fptr.write(result + '\n')
fptr.close()
|
077edb29b23c2e3fa68d2fc7cd9c5c147dc6ce3d | Mudassir-Hasan/Mysql | /books_store_sql_database_project.py | 32,946 | 3.65625 | 4 |
import mysql.connector
# class about Author:
class Author:
myDb = mysql.connector.connect(
host='localhost',
user='root',
password='Allah786??'
)
# creating the cursor object:
my_cursor = myDb.cursor()
# function to create the author table :
def create (self) :
super().create()
try:
my_cursor = self.my_cursor
# using the database :
query_2 = ('''use books_store ''')
# creating :
query_3 = ('''create table if not exists author_info (
a_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE
)''')
my_cursor.execute(query_2)
my_cursor.execute(query_3)
except Exception as e :
print(e)
# function for adding the new records of authors :
def add(self) :
try:
my_cursor = self.my_cursor
# using the database:
my_cursor.execute("use books_store;")
# loop for continuing :
while True :
print("To save record just type 'enter' ")
a_name = input("Enter the author name : ")
# conditions for breaking the loop :
if a_name.lower() == 'enter' :
break
else:
pass
# inserting is here :
query_4 = (f'''insert into author_info (name)
values
("{a_name}")''')
my_cursor.execute(query_4)
self.myDb.commit()
except Exception as e:
print(e)
# function for reading the all the records :
def read (self) :
u_input = input("Are you sure to check all records. \n--> Type 'yes'/'no' : ")
if u_input.lower() == 'yes' :
try:
my_cursor = self.my_cursor
my_cursor.execute("use books_store")
my_cursor.execute("select * from author_info ")
result = my_cursor.fetchall()
# loop for displaying :
for data in result:
print(data)
except Exception as e :
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# function for searching the record about Publisher :
def filter (self) :
# confirmation :
u_input = input("Are you sure to check author's records. \n--> Type 'yes'/'no' : ")
# conditions:
if u_input.lower() == 'yes' :
try:
a_name = input("> Please enter the name of author of which you want to check the record : ")
my_cursor = self.my_cursor
my_cursor.execute("use books_store")
my_cursor.execute(f'''select * from author_info where name like "%{a_name}%"''')
result = my_cursor.fetchall()
# loop for displaying :
for data in result:
print(data)
except Exception as e :
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# function about the updation of author table :
def update (self) :
# confirmation :
u_input = input("Are you sure to update author's records. \n--> Type 'yes'/'no' : ")
my_cursor = self.my_cursor
# conditions :
if u_input.lower() == 'yes' :
try:
a_name = input('''> ok, Now enter the name of author of which you want to update : ''')
u_name = input('''> ok, Now enter the updated name of author : ''')
my_cursor.execute("use books_store; ")
my_cursor.execute(f'''update author_info set name = "{u_name}" where name = "{a_name}" ''')
# saving the changes :
self.myDb.commit()
except Exception as e :
print(e)
else:
print("_____Process successful_____")
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# function to delete any record from author table :
def delete (self) :
# confirmation :
u_input = input("Are you sure to delete author's records. \n--> Type 'yes'/'no' : ")
my_cursor = self.my_cursor
# conditions :
if u_input.lower() == 'yes' :
try:
a_name = input('''> ok, Now enter the name of author of which you want to update : ''')
my_cursor.execute("use books_store; ")
my_cursor.execute(f'''delete from author_info where name = "{a_name}" ''')
# saving the changes :
self.myDb.commit()
except Exception as e :
print(e)
else:
print("_____Process successful_____")
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# class about Publisher:
class Publisher:
myDb = mysql.connector.connect(
host='localhost',
user='root',
password='Allah786??'
)
# creating the cursor object:
my_cursor = myDb.cursor()
# function to create the publisher's table :
def create (self) :
super().create()
try:
my_cursor = self.my_cursor
# using the database :
query_2 = ('''use books_store ''')
# creating :
query_3 = ('''create table if not exists publisher_info (
p_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE
)''')
my_cursor.execute(query_2)
my_cursor.execute(query_3)
except Exception as e :
print(e)
# function for adding the new records of publishers :
def add(self) :
try:
my_cursor = self.my_cursor
# using the database :
my_cursor.execute("use books_store;")
# loop for continuing :
while True :
print("To save record just type 'enter' ")
a_name = input("Enter the publisher name : ")
# conditions for breaking the loop :
if a_name.lower() == 'enter' :
break
else:
pass
# inserting is here :
query_4 = (f'''insert into publisher_info (name)
values
("{a_name}")''')
my_cursor.execute(query_4)
self.myDb.commit()
except Exception as e:
print(e)
# function for reading the all the records :
def read (self) :
u_input = input("Are you sure to check all records. \n--> Type 'yes'/'no' : ")
if u_input.lower() == 'yes' :
try:
my_cursor = self.my_cursor
my_cursor.execute("use books_store")
my_cursor.execute("select * from publisher_info ")
result = my_cursor.fetchall()
# loop for displaying :
for data in result:
print(data)
except Exception as e :
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# function for searching the record about the publisher using where clause :
def filter (self) :
# confirmation :
u_input = input("Are you sure to check publisher's records. \n--> Type 'yes'/'no' : ")
# conditions:
if u_input.lower() == 'yes' :
try:
a_name = input("> Please enter the name of publisher of which you want to check the record : ")
my_cursor = self.my_cursor
my_cursor.execute("use books_store")
my_cursor.execute(f'''select * from publisher_info where name like "%{a_name}%"''')
result = my_cursor.fetchall()
# loop for displaying :
for data in result:
print(data)
except Exception as e :
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# function about the updation of author table :
def update (self) :
# confirmation :
u_input = input("Are you sure to update publisher's records. \n--> Type 'yes'/'no' : ")
my_cursor = self.my_cursor
# conditions :
if u_input.lower() == 'yes' :
try:
a_name = input('''> ok, Now enter the name of publisher of which you want to update : ''')
u_name = input('''> ok, Now enter the updated name of publisher : ''')
my_cursor.execute("use books_store; ")
my_cursor.execute(f'''update publisher_info set name = "{u_name}" where name = "{a_name}" ''')
# saving the changes :
self.myDb.commit()
except Exception as e :
print(e)
else:
print("_____Process successful_____")
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# function to delete any record from author table :
def delete (self) :
# confirmation :
u_input = input("Are you sure to delete publisher's records. \n--> Type 'yes'/'no' : ")
my_cursor = self.my_cursor
# conditions :
if u_input.lower() == 'yes' :
try:
a_name = input('''> ok, Now enter the name of publisher of which you want to delete : ''')
my_cursor.execute("use books_store; ")
my_cursor.execute(f'''delete from publisher_info where name = "{a_name}" ''')
# saving the changes :
self.myDb.commit()
except Exception as e :
print(e)
else:
print("_____Process successful_____")
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# class for making a relationship between the author and Publisher:
class AuthorPublisherRelatiion :
myDb = mysql.connector.connect(
host='localhost',
user='root',
password='Allah786??'
)
# creating the cursor object:
my_cursor = myDb.cursor()
# function to create the author table :
def create (self) :
try:
my_cursor = self.my_cursor
# using the database :
query_7 = ('''use books_store; ''')
my_cursor.execute(query_7)
# creating :
query_8 = ('''create table if not exists join_ap (
aut_id INT NOT NULL,
pub_id INT NOT NULL
); ''')
my_cursor.execute(query_8)
except Exception as e :
print(e)
def add(self):
my_cursor = self.my_cursor
# using the database :
my_cursor.execute("use books_store;")
# getting all info from the user :
while True:
try:
print("_____Just type 'enter' to save the record_____")
print("_____For enter new records_|just press enter|_____")
cont_loop = input()
if cont_loop.lower() == 'enter':
break
# table columns inputs :
at_id = input("Enter the id of author : ")
pb_id = input("Enter the id of publisher : ")
# inserting the data in tables :
query_4 = ('''INSERT INTO join_ap (
aut_id,
pub_id )
VALUES (%s,%s)
''')
query_5 = at_id, pb_id
my_cursor.execute(query_4, query_5)
self.myDb.commit()
except Exception as f :
print(f)
# function for reading the all the records :
def read (self) :
u_input = input("Are you sure to check all records. \n--> Type 'yes'/'no' : ")
if u_input.lower() == 'yes' :
try:
my_cursor = self.my_cursor
my_cursor.execute("use books_store")
my_cursor.execute("select * from join_ap ")
result = my_cursor.fetchall()
# loop for displaying :
for data in result:
print(data)
except Exception as e :
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# this function is for creating a relationship between author and publisher :
def filter(self) :
# confirmation :
u_input = input("Are you sure to check the Author and publisher relationship . \n--> Type 'yes'/'no' : ")
# conditions:
if u_input.lower() == 'yes' :
try:
my_cursor = self.my_cursor
# using the database :
my_cursor.execute("use books_store")
# creating the relationship between the tables :
user_Input = int(input('''Pres 1 to the check the relationship of publishers with authors :
Press 2 to the check relationship of authors with publishers : \n'''))
if user_Input == 1 :
name = input("Enter the name of author : ")
query_11 = (f'''select a.name, pb.name
from author_info a join join_ap j
on aut_id = a.a_id
join publisher_info pb
on pub_id = pb.p_id
where a.name like "%{name}%" ''')
my_cursor.execute(query_11)
results = my_cursor.fetchall()
for data in results:
print(data)
elif user_Input == 2 :
name = input("Enter the name of publisher : ")
query_12 = (f'''select pb.name, a.name
from author_info a join join_ap j
on aut_id = a.a_id
join publisher_info pb
on pub_id = pb.p_id
where pb.name like "%{name}%" ''')
my_cursor.execute(query_12)
results = my_cursor.fetchall()
for data in results:
print(data)
except Exception as e :
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# BaseClass :
class BaseClass(Publisher, Author, AuthorPublisherRelatiion):
myDb = mysql.connector.connect(
host='localhost',
user='root',
password='Allah786??'
)
# creating the cursor object:
my_cursor = myDb.cursor()
def create(self):
try:
my_cursor = self.my_cursor
#query for creating database :
query_4 = ("create database if not exists books_store")
# query for using the database :
query_5 = ("create database if not exists books_store")
my_cursor.execute(query_4)
my_cursor.execute(query_5)
# the under super method is for the execution for the table of author and publisher :
super().create()
#query for creating books table :
query_6 = ('''create table if not exists books_info(
id INT NOT NULL,
book_name VARCHAR(100) NOT NULL,
author_id INT NOT NULL,
publisher_id INT NOT NULL,
price VARCHAR(20) NOT NULL DEFAULT "0$",
published_at YEAR NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (author_id) REFERENCES author_info (a_id),
FOREIGN KEY (publisher_id) REFERENCES publisher_info (p_id)
) ''')
my_cursor.execute(query_6)
except Exception as e :
print(e)
# function for adding the new records of publishers :
def add(self) :
my_cursor = self.my_cursor
# getting all info from the user :
while True:
try:
print("_____Just type 'enter' to save the record_____")
print("_____For enter new records_|just press enter|_____")
cont_loop = input()
if cont_loop.lower() == 'enter':
break
# table columns inputs :
id = input("Enter the id of book : ")
bookName = input('Enter the name of book : ')
# printing the id's of authors
print("Here the authors names with their id's are follows:-")
my_cursor.execute("use books_store")
my_cursor.execute("select * from author_info")
res = my_cursor.fetchall()
for row in res :
print(row)
authorName = input(f'''Now enter the id of author : ''')
# printing the id's of authors
print("Here the publishers names with their id's are follows:-")
my_cursor.execute("use books_store")
my_cursor.execute("select * from publisher_info")
rs = my_cursor.fetchall()
for row in rs :
print(row)
publisherName = input("Enter the id of book's publisher : ")
price = input("Enter the price of book with doller sign($) : ")
year = input("Enter the year of publish (like '1985') : ")
# inserting the data in tables :
query_4 = ('''INSERT INTO books_info(
id,
book_name,
author_id,
publisher_id,
price,
published_at)
VALUES (%s,%s,%s,%s,%s,%s)
''')
query_5 = id, bookName, authorName, publisherName, price, year
my_cursor.execute(query_4, query_5)
self.myDb.commit()
except Exception as f :
print(f)
# function for reading the all the records :
def read (self) :
u_input = input("Are you sure to check all records. \n--> Type 'yes'/'no' : ")
if u_input.lower() == 'yes' :
try:
my_cursor = self.my_cursor
my_cursor.execute("use books_store")
my_cursor.execute("select * from books_info ")
result = my_cursor.fetchall()
# loop for displaying :
for data in result:
print(data)
except Exception as e :
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
def filter(self):
try:
u_input = input("Are you sure to check the books records of author and publisher records. \n--> Type 'yes'/'no' : ")
if u_input.lower() == 'yes' :
my_cursor = self.my_cursor
# using the database :
my_cursor.execute("use books_store")
U_input = input('''PRESS '1' TO CHECK THE BOOKS RECORD OF AUTHOR'S : \nPRESS '2' TO CHECK THE BOOKS RECORD OF PUBLISHER'S : \n''')
if U_input == '1' :
r_name = input("Kindly enter the author name of which you want to check book's record : \n")
query = (f'''select b.book_name, b.price, b.published_at, a.name, pb.name
from books_info b join author_info a
on b.author_id = a.a_id
join publisher_info pb
on b.publisher_id = pb.p_id
where a.name like "%{r_name}%" ; ''')
my_cursor.execute(query)
results = my_cursor.fetchall()
# loop for printing the searched record :
for row in results :
print(row)
elif U_input == '2' :
p_name = input("Kindly enter the publisher name of which you want to check book's record : ")
query = (f'''select b.book_name, b.price, b.published_at, a.name, pb.name
from books_info b join author_info a
on b.author_id = a.a_id
join publisher_info pb
on b.publisher_id = pb.p_id
where pb.name like "%{p_name}%" ; ''')
my_cursor.execute(query)
results = my_cursor.fetchall()
# loop for printing the searched record :
for row in results :
print(row)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
except Exception as e :
print(e)
# function about the updation of author table :
def update (self) :
# confirmation :
u_input = input("Are you sure to update publisher's records. \n--> Type 'yes'/'no' : ")
my_cursor = self.my_cursor
# using the database :
my_cursor.execute("use books_store")
# conditions :
if u_input.lower() == 'yes' :
try:
book_name = input('Hello! dear please enter the name of book of which you want to update : ')
att = input('''Now Type
'1' for update book's name :
'2' for update author's name :
'3' for update price of book :
'4' for update published date of book :
'5' for update author id for book :
'6' for update publisher id for book: ''')
if att == '1' :
name = input('Enter the updated name : ')
my_cursor.execute(f'''update books_info set book_name = "{name}"
where book_name = "{book_name}" ''')
self.myDb.commit()
elif att == '2' :
Name = input('Enter the updated name : ')
my_cursor.execute(f'''update books_info set author_name = "{Name}"
where book_name = "{book_name}" ''')
self.myDb.commit()
elif att == '3' :
price = input('Enter the updated price : ')
my_cursor.execute(f'''update books_info set price = "{price}"
where book_name = "{book_name}" ''')
self.myDb.commit()
elif att == '4' :
year = input(f'Enter the updated year of publishing {book_name} like (1985) : ')
my_cursor.execute(f'''update books_info set published_at = "{year}"
where book_name = "{book_name}" ''')
self.myDb.commit()
elif att == '5' :
id = input(f'Enter the updated author id : ')
my_cursor.execute(f'''update books_info set author_id = "{id}"
where book_name = "{book_name}" ''')
self.myDb.commit()
elif att == '6' :
pId = input(f'Enter the updated publisher id : ')
my_cursor.execute(f'''update books_info set publisher_id = "{pId}"
where book_name = "{book_name}" ''')
self.myDb.commit()
except Exception as e:
print(e)
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# function to delete any record from author table :
def delete (self) :
# confirmation :
u_input = input("Are you sure to delete book's records. \n--> Type 'yes'/'no' : ")
my_cursor = self.my_cursor
# conditions :
if u_input.lower() == 'yes' :
try:
b_name = input('''> ok, Now enter the name of book of which you want to delete : ''')
my_cursor.execute("use books_store; ")
my_cursor.execute(f'''delete from books_info where book_name = "{b_name}" ''')
# saving the changes :
self.myDb.commit()
except Exception as e :
print(e)
else:
print("_____Process successful_____")
elif u_input == 'no':
print("*****THANK YOU*****")
else :
pass
# creating object for baseclass:
books_instance = BaseClass()
# calling the create function :
books_instance.create()
# other object instansiations:
author_instance = Author()
publisher_instance = Publisher()
author_publisher_instance = AuthorPublisherRelatiion()
try:
# getting the name of user :
name = input("Hello! Buddy \nI hope you will be alright \nPlease enter your name : \n")
# printing the name of user also getting the input about what he\she want to do :
while True :
user_input = input(f'''Well {name},
Type 'a' for enter a new records :
Type 'r' for read all records :
Type 's' for search any record from saved records :
Type 'u' for update any record :
Type 'd' for update any record :
Type 'exit' for exit this session : \n''')
# conditions for continuety of program :
if user_input.lower() == 'exit':
u_in = input("Do you want to exit? \n yes / no ")
if u_in.lower() == 'yes' :
break
else :
pass
elif user_input.lower() == 'a' :
print("_oK_")
U_input = input('''Now
Press '1' to add a record of book's author :
Press '2' to add a record of book's publisher :
Press '3' to add a relationship between Author and Publisher :
Press '4' to add a record of books :
''')
# conditions for adding record :
if U_input == '1' :
author_instance.add()
if U_input == '2' :
publisher_instance.add()
if U_input == '3' :
author_publisher_instance.add()
if U_input == '4' :
books_instance.add()
elif user_input.lower() == 'r' :
print("_oK_")
U_input = input('''Now
Press '1' to read a record of book's author :
Press '2' to read a record of book's publisher :
Press '3' to read a relationship between Author and Publisher :
Press '4' to read a record of books :
''')
# conditions for adding record :
if U_input == '1' :
author_instance.read()
if U_input == '2' :
publisher_instance.read()
if U_input == '3' :
author_publisher_instance.read()
if U_input == '4' :
books_instance.read()
elif user_input.lower() == 's' :
print("_oK_")
U_input = input('''Now
Press '1' to search any record of book's author :
Press '2' to search any record of book's publisher :
Press '3' to search any relationship between Author and Publisher :
Press '4' to search any record of books :
''')
# conditions for searching record :
if U_input == '1' :
author_instance.filter()
if U_input == '2' :
publisher_instance.filter()
if U_input == '3' :
author_publisher_instance.filter()
if U_input == '4' :
books_instance.filter()
elif user_input.lower() == 'u' :
print("_oK_")
U_input = input('''Now
Press '1' to update any record of book's author :
Press '2' to update any record of book's publisher :
Press '3' to update any record of books :
''')
# conditions for updating record :
if U_input == '1' :
author_instance.update()
if U_input == '2' :
publisher_instance.update()
if U_input == '3' :
books_instance.filter()
elif user_input.lower() == 'd' :
print("_oK_")
U_input = input('''Now
Press '1' to delete any record of book's author :
Press '2' to delete any record of book's publisher :
Press '3' to delete any record of books :
''')
# conditions for deleting record :
if U_input == '1' :
author_instance.delete()
if U_input == '2' :
publisher_instance.delete()
if U_input == '3' :
books_instance.delete()
except Exception as e :
print(e)
else:
print("_____Process successful_____") |
d77e1d4bb8a9d20f80eb43981f3e06ab2bbbaf9d | kersky98/stud | /coursera/pythonHse/third/10.py | 521 | 3.890625 | 4 | # Даны действительные коэффициенты a, b, c, при этом a != 0. Решите
# квадратное уравнение ax²+bx+c=0 и выведите все его корни.
import math
a = float(input())
b = float(input())
c = float(input())
d = b**2 - 4*a*c
if d > 0:
x1 = (-b - math.sqrt(d)) / (2*a)
x2 = (-b + math.sqrt(d)) / (2*a)
if x1 > x2:
print(x2, x1)
else:
print(x1, x2)
elif d == 0:
x = -b / (2*a)
print(x)
|
5ee23fefe3969639ebb99a7f5bf4c0df71985e74 | jessicamunga/witchallenges2_DayFour | /DayFour1.py | 131 | 3.921875 | 4 | def sum(numbers):
total=0
for x in numbers:
total += x
return total
print(sum([8,2,3,0,7])) |
f16f53062e43506e87b19a70d2a0aa77e2c68a99 | Psp29/basic-python | /chapter 6/08_pract_05.py | 203 | 4.21875 | 4 | names = ["prasad", "amar", "akhbar", "anthony"]
name = input("Enter the name to check: ")
if name in names:
print("Entered name is in the list!")
else:
print("Entered name is not in the list!")
|
b112929c1836af29d6fe388e1fc749a47695c84e | arpine58/python_homework | /homework3/Palindrome numbers.py | 320 | 3.84375 | 4 | a = int(input())
b = int(input())
def palindrome(x):
temp = x
rev = 0
while x > 0:
dig = x % 10
rev = rev*10+dig
x = x//10
if temp == rev:
return True
else:
return False
for i in range(a, b):
if palindrome(i) is True:
print(i)
|
f4393ae506528879897ee1fd0bce6cb13facec8e | gthomson31/Learning | /python/Basics/lists_and_dict/tuples.py | 148 | 3.65625 | 4 | # tuples are immutable and values cannot be changed
t = (1,2,3)
mylist = [1,2,3]
print (type(t))
print (t[2])
t = ('a','a','b')
print (t.count)
|
eca4cd19c4980c376e2a358d298b037965dcb782 | BZAghalarov/Hackerrank-tasks | /Cracking coding interview/10 Sorting Bubble Sort.py | 623 | 3.953125 | 4 |
'''
https://www.hackerrank.com/challenges/ctci-bubble-sort/problem
'''
#!/bin/python3
# Complete the countSwaps function below.
def countSwaps(arr):
k = len(arr)
cnt_op = 0
for i in range(k):
for j in range(k-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
cnt_op +=1
print('Array is sorted in '+ str(cnt_op)+ ' swaps.')
print('First Element: ' + str(arr[0]))
print('Last Element: ' + str(arr[len(arr)-1]))
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().rstrip().split()))
countSwaps(a)
|
8e1b30f95c4345a2a8034f7b27d79dc629d5813d | ubi-python/study | /euler/problem5/chjsik.py | 251 | 3.796875 | 4 | result = 2
def gcd(a, b):
while b != 0:
remainder = a % b
a = b
b = remainder
return abs(a)
def lcm(a, b):
return abs((a * b) / gcd(a, b))
for i in range(2, 20):
result = lcm(result, i + 1)
print(result)
|
8f2b73ac5bc4ff224b23c8a12ecf68db2cfefc0e | gbrs/EGE_current | /#8 27539.py | 1,019 | 3.625 | 4 | '''
Задание 8 № 27539
Борис составляет 6-буквенные коды из букв Б, О, Р, И, С.
Буквы Б и Р нужно обязательно использовать ровно по одному разу,
букву С можно использовать один раз или не использовать совсем,
буквы О и И можно использовать произвольное количество раз или не использовать совсем.
Сколько различных кодов может составить Борис?
'''
lst = []
for i in 'БОРИС':
for j in 'БОРИС':
for k in 'БОРИС':
for l in 'БОРИС':
for m in 'БОРИС':
for n in 'БОРИС':
lst.append(i + j + k + l + m + n)
cnt = 0
for word in lst:
if not (word.count('Б') != 1 or word.count('Р') != 1 or word.count('С') > 1):
cnt += 1
print(cnt)
|
21171ae4785925406936e953ab93431a550a452c | yekingyan/Flask_for_my_web | /test.py | 76 | 3.53125 | 4 | d1 = {'x': 1, 'y': 2, 'z': 3}
d2 = {k: v for (k, v) in d1.items()}
print(d2) |
de1995513527ef736a83611d8db0a5cc9e8d953e | educa2ucv/Material-Apoyo-Python-Basico | /Codigos/8-Extras/Extras4.py | 624 | 3.75 | 4 | class Persona:
def __init__(self,nombre):
self.nombre = nombre
def saludo1(self):
print("Hola, soy una persona")
class Empleado:
def __init__(self,sueldo):
self.sueldo = sueldo
def saludo2(self):
print("Hola, soy un empleado")
class Cajero(Persona,Empleado):
def __init__(self,nombre,sueldo,nro_caja):
Persona.__init__(self,nombre)
Empleado.__init__(self,sueldo)
self.nro_caja = nro_caja
def saludo3(self):
print("Hola, soy un cajero")
yo = Cajero("Alexanyer",2500,5)
yo.saludo1()
yo.saludo2()
yo.saludo3() |
205b5eaca3b4bcf7759903945cabdb14fef7810f | xie233/ComputerGraphics | /line_bresenham.py | 794 | 3.921875 | 4 | from graphics import *
import time
def MidpointLine(x1,y1,x2,y2):
dx=x2-x1
dy=y2-y1
d=2*dy-dx
incrE=2*dy
incrNE=2*(dy-dx)
x=x1
y=y1
win = GraphWin('Brasenham Line', 600, 480)
PutPixle(win, x, y)
while x < x2:
if (d<= 0):
d=d+incrE
x=x+1
else:
d=d+incrNE
x=x+1
y=y+1
time.sleep(0.01)
PutPixle(win, x, y)
def PutPixle(win, x, y):
""" Plot A Pixle In The Windows At Point (x, y) """
pt = Point(x,y)
pt.draw(win)
def main():
x1 = int(input("Enter Start X: "))
y1 = int(input("Enter Start Y: "))
x2 = int(input("Enter End X: "))
y2 = int(input("Enter End Y: "))
MidpointLine(x1, y1, x2, y2)
if __name__ == "__main__":
main()
|
df31e1cb1cf26b88d50bc0cd3758aed7eb8e4828 | mdhatmaker/Misc-python | /interview-prep/geeks_for_geeks/dynamic_programming/ugly_numbers.py | 491 | 3.890625 | 4 | import sys
# return nth ugly number (number whose only prime factors are 2, 3, 5 -- 1 is ugly by default)
# first 11 ugly numbers: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …
def ugly_number(n):
ugly = [0] * n
ugly[0] = 1 # 1 is ugly number by default
for i in range(1, n-3, 3):
ugly[i] = 2 * ugly[i-1]
ugly[i+1] = 3 * ugly[i-1]
ugly[i+2] = 5 * ugly[i-1]
print(ugly[i], ugly[i+1], ugly[i+2])
if __name__ == "__main__":
print(ugly_number(11))
|
d4186e83271170d9cc66698b4dcf64e84fd18677 | heuzin/interview-codes | /adjacentElementsProduct.py | 361 | 3.96875 | 4 | # Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
def adjacentElementsProduct(inputArray):
x = 0
y = 0
p = float('-inf')
for i in range(len(inputArray) - 1):
x = inputArray[i]
y = inputArray[i + 1]
if x * y > p:
p = x * y
return p |
6aabb04631d57cbd43d9f0e49f78095efac86edd | RanchDress/EatWhere | /eatwhere.py | 2,387 | 3.6875 | 4 | import json
import datetime
import random
from enum import Enum
class Weekday(Enum):
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
restaurants = {}
preferences = {}
people_going = input("Who's going? (separated by spaces)\n").split(" ")
restaurants_file = "./restaurants.json"
preferences_file = "./preferences.json"
with open(restaurants_file) as json_file:
restaurants = json.load(json_file)
with open(preferences_file) as json_file:
preferences = json.load(json_file)
today = datetime.datetime.today().isoweekday()
preferences_going = {}
# Filter preferences by people going
for person_name, person_preferences in preferences.items():
if (person_name in people_going):
preferences_going[person_name] = person_preferences
valid_restaurant_names = []
valid_restaurant_weights = []
# Filter and weigh restaurants
for restaurant_name, restaurant_data in restaurants.items():
# Filter restaurants that are closed
is_open = False
for open_day in restaurant_data["open"]:
if Weekday(today).name == open_day.upper():
is_open = True
if not (is_open):
continue
is_vetoed = False
net_weight = 0
weight_modifier = 1/len(preferences_going)
for person_name, person_preferences in preferences_going.items():
# Filter vetoed restaurants
if (restaurant_name in person_preferences["veto"]):
is_vetoed = True
break
if (restaurant_data["cuisine"] in person_preferences["veto"]):
is_vetoed = True
break
# Add and Subtract weights based on preferences
# Things you dislike about a place probably outweigh things you like
if (restaurant_name in person_preferences["dislike"] or restaurant_data["cuisine"] in person_preferences["dislike"]):
net_weight -= weight_modifier
if (restaurant_name in person_preferences["prefer"] or restaurant_data["cuisine"] in person_preferences["prefer"]):
net_weight += weight_modifier
if (is_vetoed):
continue
valid_restaurant_names.append(restaurant_name)
valid_restaurant_weights.append(net_weight + 1)
# Get a random restaurant based on weight
random_restaurant = random.choices(valid_restaurant_names, valid_restaurant_weights)
print(random_restaurant[0]) |
fc7644383c2c201df0826096f54960beb603a0a6 | r0ttan/AoC2020 | /day2.py | 1,321 | 3.578125 | 4 | import re
test = ['1-3 a: abcde','1-3 b: cdbefg','2-9 c: acaaaaaaca']
def solve(data):
count = 0
for p in data:
p = p.split() # split on whitespace to separate parts of input
a = p[0].split('-') # extract numbers separated by -
pol = re.findall(f'{p[1][0]}', p[2]) # create list of all ocurrences
if int(a[0]) <= len(pol) <= int(a[1]): # compare numbers with length of resulting list from regexp above
count += 1
return count
def solve2(data):
count = 0
for p in data:
p = p.split()
a = [int(i) for i in p[0].split('-')]
pwd = p[2] # for readability, extract password string and control character in own variables
char = p[1][0]
if a[1] <= len(pwd):
if pwd[a[0]-1] == char and pwd[a[1]-1] != char:
count += 1
elif pwd[a[0]-1] != char and pwd[a[1]-1] == char:
count += 1
return count
def getdata(filename):
with open(filename) as f:
return [l.strip() for l in f.readlines()]
if __name__ == '__main__':
pwdpolicy = (getdata('data_d2.txt'))
print(solve(pwdpolicy))
print(solve2(pwdpolicy))
#solve2(test)
|
3e9f503c1b2e9e28fa06688a2e0ea910efc9603d | hessio/pythonExamples | /HissingMicrophone.py | 189 | 3.890625 | 4 | string = str(input())
flag = 0
for i in range(1, len(string)):
if string[i] == 's' and string[i - 1] == 's':
flag = 1
if flag == 1:
print("hiss")
else:
print("no hiss")
|
a84ed49de2e47983eab6fe2786f4900f4a706dca | clemwek/ande_bc_18 | /day1/prime_numbers/prime.py | 1,238 | 4.21875 | 4 | def gen_prime(upper_limit):
"""
A function that generates prime numbers
First check if its greater than 2 since 2 is the smallest prime number
create list to hold the variables
Then iterate through integers btn 2 and n
since 2 is the first prime number we add it to the prime list
the for loop checks if it has divisors less than its square root if it finds its added in not_prime number
the remaining numbers are primes and are saved in prime list
am using Sieve of Eratosthenes formula---where you go through odd numbers and ruling out if they have divisors
:param upper_limit: int
:return: list of prime numbers
"""
try:
upper_limit = int(upper_limit)
if upper_limit >= 2:
not_prime = []
prime = []
for i in range(2, upper_limit + 1):
if i not in not_prime:
prime.append(i)
for j in range(i * i, upper_limit + 1, i):
not_prime.append(j)
return prime
else:
return "prime numbers are positive and greater than one!"
except ValueError:
return 'Wrong entry'
except TypeError:
return 'Wrong entry'
|
8367dbd9be20eb4bd5dc88ba06b582fede74b809 | pralhad88/ProjectEluer | /project2.py | 1,043 | 3.71875 | 4 |
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
from functools import lru_cache #LRU CACHE (LEAST REENTLY USED CACHE) used for reduced time taken by excution of program because we are cheacking the condithion upto 4 million..
@lru_cache(maxsize = 1000)
def fib(n):
if n==1:
return 1
elif n==2:
return 1
elif n>2:
return fib(n-1) + fib(n-2)
n=1
sum=0
while True:
if fib(n)%2==0:
sum=sum+fib(n)
if fib(n) >= 4000000:
break
n+=1
print(sum)
# YOU CAN SOLVE DIFFERNT WAY ALSO, AS GIVEN BELOW.
first_number=1
next_number=0
sum=0
counter = 0
while True:
if first_number % 2 == 0:
sum+=first_number
if first_number >= 4000000:
break
addition = first_number + next_number
next_number = first_number
first_number = addition
counter+=1
print(sum)
|
17b5161a3f78d6f4c8299383a494413ccbe9215a | kr-MATAGI/coursera | /2-NLP_with_Probabilistic_Models/Week_3/Assignment/Autocomplete/suggest_a_word.py | 3,667 | 3.890625 | 4 | # UNQ_C11 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: suggest_a_word
def suggest_a_word(previous_tokens, n_gram_counts, n_plus1_gram_counts, vocabulary, k=1.0, start_with=None):
"""
Get suggestion for the next word
Args:
previous_tokens: The sentence you input where each token is a word. Must have length > n
n_gram_counts: Dictionary of counts of n-grams
n_plus1_gram_counts: Dictionary of counts of (n+1)-grams
vocabulary: List of words
k: positive constant, smoothing parameter
start_with: If not None, specifies the first few letters of the next word
Returns:
A tuple of
- string of the most likely next word
- corresponding probability
"""
# length of previous words
n = len(list(n_gram_counts.keys())[0])
# From the words that the user already typed
# get the most recent 'n' words as the previous n-gram
previous_n_gram = previous_tokens[-n:]
# Estimate the probabilities that each word in the vocabulary
# is the next word,
# given the previous n-gram, the dictionary of n-gram counts,
# the dictionary of n plus 1 gram counts, and the smoothing constant
probabilities = estimate_probabilities(previous_n_gram,
n_gram_counts, n_plus1_gram_counts,
vocabulary, k=k)
# Initialize suggested word to None
# This will be set to the word with highest probability
suggestion = None
# Initialize the highest word probability to 0
# this will be set to the highest probability
# of all words to be suggested
max_prob = 0
### START CODE HERE (Replace instances of 'None' with your code) ###
# For each word and its probability in the probabilities dictionary:
for word, prob in probabilities.items(): # complete this line
# If the optional start_with string is set
if start_with: # complete this line
# Check if the beginning of word does not match with the letters in 'start_with'
if word[0] != start_with: # complete this line
# if they don't match, skip this word (move onto the next word)
continue # complete this line
# Check if this word's probability
# is greater than the current maximum probability
if max_prob < prob: # complete this line
# If so, save this word as the best suggestion (so far)
suggestion = word
# Save the new maximum probability
max_prob = prob
### END CODE HERE
return suggestion, max_prob
# test your code
sentences = [['i', 'like', 'a', 'cat'],
['this', 'dog', 'is', 'like', 'a', 'cat']]
unique_words = list(set(sentences[0] + sentences[1]))
unigram_counts = count_n_grams(sentences, 1)
bigram_counts = count_n_grams(sentences, 2)
previous_tokens = ["i", "like"]
tmp_suggest1 = suggest_a_word(previous_tokens, unigram_counts, bigram_counts, unique_words, k=1.0)
print(f"The previous words are 'i like',\n\tand the suggested word is `{tmp_suggest1[0]}` with a probability of {tmp_suggest1[1]:.4f}")
print()
# test your code when setting the starts_with
tmp_starts_with = 'c'
tmp_suggest2 = suggest_a_word(previous_tokens, unigram_counts, bigram_counts, unique_words, k=1.0, start_with=tmp_starts_with)
print(f"The previous words are 'i like', the suggestion must start with `{tmp_starts_with}`\n\tand the suggested word is `{tmp_suggest2[0]}` with a probability of {tmp_suggest2[1]:.4f}") |
d13d3f4257c2c33ae7f400d51ee257147c7a39bf | CJ8664/leetcode | /746-min-cost-climbing-stairs/746-min-cost-climbing-stairs.py | 673 | 3.609375 | 4 | class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
for i in range(2, len(cost)):
# To cost[i] represents the cost you need to pay to get to next
# step starting from i.
# But to get to step i, you need to pay some cost.
# That is pay the cost from
# - second last step and take two steps
# - last step and take one step
cost[i] += min(cost[i-2], cost[i-1])
# Once you are at the end of array the result is minimum of
# cost to get to last step or second last step
return min(cost[-1], cost[-2])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.