blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fd65c86c0d24d699c51bbec67154cfd5382fd7c5 | tseiiti/curso_em_video | /mundo_1/ex013.py | 331 | 3.609375 | 4 | from os import system, name
system('cls' if name == 'nt' else 'clear')
dsc = ('''DESAFIO 013:
Faça um algoritmo que leia o salário de um funcionário e mostre seu
novo salário, com 15% de aumento.
''')
n = float(input('Digite o salário atual: R$ '))
print('o novo salário com 15% de aumento é: R$ {:.2f}'.format(n * 1.15))
|
13faca636197c11ca123b8058a0d10a2527e3eca | acemodou/Working-Copy | /DataStructures/v1/code/leet/Heaps/merge_sorted_arrays.py | 943 | 3.890625 | 4 | def mergeSortedArrays(arrays):
current_positions = [0 for _ in arrays]
sorted_list = []
while True:
smallest_list_of_elements = []
for idx in range(len(arrays)):
sub_arrays = arrays[idx]
element_idx = current_positions[idx]
if element_idx == len(sub_arrays):
continue
smallest_list_of_elements.append({"array_idx" : idx, "value" : sub_arrays[element_idx]})
if len(smallest_list_of_elements) == 0:
break
min_value = get_minimum(smallest_list_of_elements)
current_positions[min_value["array_idx"]] +=1
sorted_list.append(min_value["value"])
return sorted_list
def get_minimum(items):
min_value_idx = 0
for idx in range(1, len(items)):
if items[idx]["value"] < items[min_value_idx]["value"]:
min_value_idx = idx
return items[min_value_idx]
|
a496ac74beb212620225adeb18fa9ad58c9a66ec | Lbabichev17/python_practice | /courses/Алгоритмы теория и практика. Структуры данных/5. Максимум в скользящем окне.py | 1,749 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# def max_in_window(arr, size):
# if size == 1:
# yield from arr
# return
# for i in range(len(arr) - size + 1):
# max_ = max(arr[i + 1: i + size])
# last_max = arr[i] if arr[i] > max_ else max_
# yield last_max
# def max_in_window(arr, size):
# if size == 1:
# yield from arr
# return
# maxs = [max(arr[i: i + 2]) for i in range(size - 1)]
# yield max(maxs)
# del arr[:size-1]
# for i in range(len(arr)-1):
# del maxs[0]
# maxs.append(max(arr[0: 2]))
# del arr[0]
# yield max(maxs)
# from collections import deque
# def max_in_window(arr, size):
# if size == 1:
# yield from arr
# return
# queue = deque(arr[:size-1], size)
# for i in range(size - 1, len(arr)):
# queue.append(arr[i])
# yield max(queue)
# def max_in_window(arr, size):
# if size == 1:
# yield from arr
# return
# yield from (max(arr[i: i + size]) for i in range(len(arr) - size + 1))
def max_in_window(arr, size):
if size == 1:
yield from arr
return
else:
for i in range(len(arr) - size + 1):
yield max(arr[i: i + size])
if __name__ == '__main__':
print(list(max_in_window([2, 7, 3, 1, 5, 2, 6, 2], 4)))
assert list(max_in_window([2, 7, 3, 1, 5, 2, 6, 2], 4)) == [7, 7, 5, 6, 6]
assert list(max_in_window([2, 1, 5], 1)) == [2, 1, 5]
assert list(max_in_window([2, 3, 9], 3)) == [9]
assert list(max_in_window([2, 1, 5], 2)) == [2, 5]
# для ввода при тестировании на сайте
# input()
# print(*max_in_window(list(int(i) for i in input().split()), int(input())))
|
5993bd4791817f7b42a53989f7170c1e864015c7 | GavinMendelGleason/code | /python/cs2bc1/lecture9.py | 4,512 | 3.890625 | 4 | #!/usr/bin/env python
## Natural language problem description
"""A customer can browse through the product catalog and add the items to a shopping cart. He can proceed to the checkout as long as his shopping cart is not empty. A customer is required to login to the system when proceeding to the checkout or create an account if one does not already exist.
The order will be charged to the credit card associated with customer's account. The customer needs to provides his full name, email address, phone number, credit card and billing address details when creating an account.
A customer can login to the system to maintain his account information, such as changing phone number, address, and credit card details, or check the status of his orders.
Upon order receipt, the shop sales staff will process the order by charging the customer's credit card. Once the order has been charged, he will then mark the order as paid and pass the goods to a courier company for delivery to the customer. If any item ordered is out of stock then the order will be marked as on hold.
The courier company will pack the item with standard packaging unless the order is marked as gift in which case the items are packaged as gift items.
If an item arrives damaged, the customer can return it by registering it in the online shop. The courier company will collect the item from customer and the sales staff will refund the money for that item.
The Marketing staff are responsible for maintaining the product catalog. They can also setup the promotion item list and send promotion emails to customers."""
## The OO way
class Catalogue:
def __init__(self,stock=None):
if stock:
self.stock = stock
else:
self.stock = {'t-shirt' : 1,
'poster' : 2}
def list_contents(self):
return self.stock
def restock(self,item,number):
if item in self.stock:
self.stock[item] += number
else:
self.stock[item] = number
def destock(self,item,number):
if item in self.stock and self.stock[item] > number:
self.stock[item] -= number
return True
else:
return False
class ShoppingCart:
def __init__(self):
self.shopping_cart = {}
def add_item(self,item):
if item in self.shopping_cart:
self.shopping_cart[item] += 1
else:
self.shopping_cart[item] = 1
def checkout(self):
if len(self.shopping_cart) > 0:
print "we will bill you now"
"Code goes here...."
else:
print "You have nothing in your cart"
class Server:
def __init__(self):
self.registered = {}
self.shopping_carts = {}
def register(self,user,passwd):
if user in self.registered:
return False
else:
self.registered[user]=passwd
self.shopping_carts[user] = ShoppingCart()
return True
def registered(self,user):
return self.registered[user]
def authorise(self,user,passwd):
if user in self.registered:
return self.registered[user] == passwd and self.shopping_carts[user]
else:
return False
class Customer:
def __init__(self,catalogue,server):
self.catalogue = catalogue
self.server = server
self.shopping_cart = None
def browse(self):
return self.catalogue.list_contents()
def login(self,user,passwd):
cart = self.server.authorise(user,passwd)
if cart:
self.shopping_cart = cart
return True
else:
return False
def register(self,user,passwd):
return self.server.register(user,passwd)
def logged_in(self):
return self.shopping_cart
def select(self,item):
if self.logged_in():
res = self.catalogue.destock(item,1)
if res:
self.shopping_cart.add(item)
return True
else:
print "Out of stock"
return False
else:
print "Not logged in"
return False
if __name__ == "__main__":
server = Server()
catalogue = Catalogue()
customer = Customer(catalogue,server)
customer.register("me","pass")
customer.login("me","pass")
customer.browse()
customer.select('t-shirt')
|
18e8fbd87af7b9985b2136d1e177cacb8b378706 | indraputra147/pythonworkbook | /chapter2/ex41.py | 499 | 4.4375 | 4 | #Exercise 41: Classifying Triangles
"""
The program reads the length of the three sides of a triangle from the user
display a message that states the triangle's type
equilateral or isosceles or scalene
"""
print("Enter the three sides of a triangle!")
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
if a == b == c:
print("The triangle is Equilateral")
elif a == b or b == c or a == c:
print("The triangle is Isosceles")
else:
print("The triangle is Scalene")
|
202ebb0f6c1d31a82eace7674df720edf6ce4001 | operation-lakshya/BackToPython | /MyOldCode-2008/JavaBat(now codingbat)/Strings1/n Twice.py | 217 | 3.78125 | 4 |
s=raw_input("\nEnter a string\t")
n=int(raw_input("\nEnter 'n input':\t"))
if (n>len(s)):
print "\n'n input' is grater than the string length"
else:
print s[:n]+s[(len(s)-n):]
raw_input("\nPress enter to finish") |
2bf65a3b95c1dc9caf9ddf51b1832fb445b3dad9 | arnabs542/Leetcode-18 | /186. Reverse Words in a String II.py | 765 | 3.796875 | 4 | class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
l, r = 0, 0
while r < len(s):
if s[r] == ' ':
s[l:r] = s[l:r][::-1]
l = r + 1
r += 1
s[l:r] = s[l:r][::-1]
return
'''
Given an input string , reverse the string word by word.
Note:
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?
Solution: Python list slice, in place
Time: O(n)
Space: O(1)
'''
|
e49ebd6256930eaeb46b9ebc33e98c6e1cf1c983 | imzhen/Leetcode-Exercise | /src/container-with-most-water.py | 1,154 | 3.765625 | 4 | #
# [11] Container With Most Water
#
# https://leetcode.com/problems/container-with-most-water
#
# Medium (36.16%)
# Total Accepted: 115284
# Total Submissions: 318834
# Testcase Example: '[1,1]'
#
# Given n non-negative integers a1, a2, ..., an, where each represents a point
# at coordinate (i, ai). n vertical lines are drawn such that the two endpoints
# of line i is at (i, ai) and (i, 0). Find two lines, which together with
# x-axis forms a container, such that the container contains the most water.
#
# Note: You may not slant the container and n is at least 2.
#
#
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
lo, hi = 0, len(height) - 1
result = min(height[0], height[-1]) * (hi - lo)
while lo < hi:
area_curr = min(height[lo], height[hi]) * (hi - lo)
result = max(area_curr, result)
if height[lo] < height[hi]:
lo += 1
elif height[lo] > height[hi]:
hi -= 1
else:
lo += 1
hi -= 1
return result
|
141d5630c828d55a94b00b67ba338ed62d24d712 | sirhaug/fellesprosjekt | /KTN/json_examples.py | 541 | 4.375 | 4 | '''
Examples of working with JSON
KTN 2013 / 2014
'''
import json
'''
Converting a dictionary object to a JSON string:
'''
my_value = 3
my_list = [1, 2, 5]
my_dict = {'key': my_value, 'key2': my_list}
my_dict_as_string = json.dumps(my_dict)
print my_dict_as_string
'''
Output:
{"key2": [1, 2, 5], "key1": 3}
'''
'''
Converting a JSON string to a dictionary object:
'''
my_value = 3
my_list = [1, 2, 5]
my_dict = {'key': my_value, 'key2': my_list}
my_dict_as_string = json.dumps(my_dict)
my_dict_from_string = json.loads(my_dict_as_string)
|
164dae36315b12831e862e29e2c516001632ad96 | VaishnaviReddyGuddeti/Python_programs | /Python_Lists/LoopThroughaList.py | 174 | 4.375 | 4 | # You can loop through the list items by using a for loop:
# Print all items in the list, one by one:
thislist = ["apple", "orange", "cherry"]
for x in thislist:
print(x)
|
24cafc51d48b53937509a1d49d95a3aaafd83e97 | mihransimonian/Excercises-Math-Project-Euler | /Solved/Excercise_7_Solution_2.py | 416 | 3.609375 | 4 | # Excercise 7, alternative, significantly quicker solution
def is_prime(n):
nums_to_check = range(2, int(n**.5) + 1)
for i in nums_to_check:
if n % i == 0:
return False
return True
def prime_at_index(idx):
n_primes = 1
n = 2
while n_primes < idx:
n+=1
if is_prime(n):
n_primes += 1
return n
print(prime_at_index(10001))
# Answer: 104743 |
c17c8fede04679f8cc6f522d3ca56fd8dde399a8 | Nitinvasudevan/lecture2 | /flight.py | 557 | 3.796875 | 4 | class Flight ():
def __init__(self,capcity):
self.capacity = capcity
self.passangers = []
def add_passangers (self,name):
if not self.open_seats():
return False
self.passangers.append(name)
return True
def open_seats(self):
return self.capacity - len(self.passangers)
flight = Flight(3)
people = ["A", "B", "C", "D"]
for i in people:
if flight.add_passangers(i):
print(f"Was able to add person {i}")
else:
print(f"Was not able to add person {i}. All Full") |
9dcd55d218527467ca607165fce3cc54d55ef0bf | whgusdn321/Competitive-programming | /leetcode/validateBinarySeachTree.py | 1,212 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def dfs(self, node: TreeNode) -> bool:
if node.left and node.right:
lmin, lmax = self.dfs(node.left)
rmin, rmax = self.dfs(node.right)
if lmax < node.val < rmin:
return (lmin, rmax)
else:
return (-2e11, 2e11)
elif node.left:
lmin, lmax = self.dfs(node.left)
if lmax < node.val:
return (lmin, node.val)
else:
return (-2e11, 2e11)
elif node.right:
rmin, rmax = self.dfs(node.right)
if node.val < rmin:
return (node.val, rmax)
else:
return (-2e11, 2e11)
else:
return (node.val, node.val)
def isValidBST(self, rootNode):
if not rootNode:
return True
x = self.dfs(rootNode)
if x != (-2e11, 2e11):
print(x)
return True
else:
return False
|
204a130f1f91bc66c642aa3b6945402a5049fdb5 | Camilo1318/EjerciciosPython | /Condicionales/Ejercicio8.py | 3,347 | 4.0625 | 4 | #En una determinada empresa, sus empleados son evaluados al final de cada año. Los puntos que pueden obtener en la evaluación comienzan en 0.0 y pueden ir aumentando, traduciéndose en mejores beneficios. Los puntos que pueden conseguir los empleados pueden ser 0.0, 0.4, 0.6 o más, pero no valores intermedios entre las cifras mencionadas. A continuación se muestra una tabla con los niveles correspondientes a cada puntuación. La cantidad de dinero conseguida en cada nivel es de 2.400€ multiplicada por la puntuación del nivel.
#Nivel Puntuación
#Inaceptable 0.0
#Aceptable 0.4
#Meritorio 0.6 o más
#Escribir un programa que lea la puntuación del usuario e indique su nivel de rendimiento, así como la cantidad de dinero que recibirá el usuario.
#Yosi
valoracion = float(input("Por favor introduzca su puntuación como empleado: "))
def Calcular_Nivel(valoracion):
dinero = 2400*valoracion + 2400
if valoracion == 0.0:
print(f"Su nivel es Inaceptable con una prima de 2400 ")
elif valoracion == 0.4:
print(f"Su nivel es Aceptable con una prima de {dinero} ")
elif valoracion >= 0.6:
print(f"Su nivel es Meritorio con una prima de {dinero} ")
Calcular_Nivel(valoracion)
#Juan Diego
evaluacion = float(input("Introduzca la puntuacion del empleado (0.0 , 0.4 o 0.6): "))
beneficio = 2400*evaluacion + 2400
def puntaje(evaluacion):
if evaluacion == 0.0:
return f"Este es su beneficio: {beneficio}"
elif evaluacion == 0.4:
return f"Este es su beneficio: {beneficio}"
elif evaluacion >= 0.6:
return f"Este es su beneficio: {beneficio}"
else:
return "Introduzca un valor valido"
print(puntaje(evaluacion))
#Cristian Pérez
puntuacion = float(input("Ingrese su puntuacion: "))
dinero = 2400
if((puntuacion == 0.0 or 0.4 or 0.6) or puntuacion>0.6):
if puntuacion == 0.0:
print(f"Su nivel es Inaceptable: {dinero*(puntuacion+1)}")
elif puntuacion == 0.4:
print(f"Su nivel es Aceptable: {dinero*(puntuacion+1)}")
elif puntuacion >= 0.6:
print(f"Su nivel es Meritorio: {dinero*(puntuacion+1)}")
else:
print("Puntuacion invalida")
#lis ¿Si te funciona ya? si muchas gracias
puntuacion = float(input ("ingresar la puntuacion obtenida "))
def valor_dinero(puntuacion):
print( 2400+(2400*puntuacion))
def rendimiento(puntuacion):
if puntuacion == 0.0:
print ("el rendimiento es inaceptable y la cantidad de dinero recibida es de: ", valor_dinero(puntuacion))
elif puntuacion == 0.4 :
print ("el rendimiento es aceptable y la cantidad de dinero recibida es de: ", valor_dinero(puntuacion))
elif puntuacion>= 0.6 :
print ("el rendimiento es meritorio y la cantidad de dinero recibida es de: ", valor_dinero(puntuacion))
else:
print ("el valor no es valido")"
rendimiento(puntuacion)
#Debes de imprimir lo que tienes dentro de la función, o si vas a utilizar el return debes imprimirlo donde lo vas a utilizar.
#Juan David
puntuacion = float(input("¿cual es su puntuacion?: "))
def nivel(puntuacion):
prima = 2400*puntuacion+1
if puntuacion == 0.0:
print(f"Su nivel es Inaceptable ")
elif puntuacion == 0.4:
print(f"Su nivel es Aceptable con una prima de {prima} ")
elif puntuacion >= 0.6:
print(f"Su nivel es Meritorio con una prima de {prima} ")
nivel(puntuacion)
|
52551d23ad5fd549bb5fb26e2a6afa8c0234c34e | josemorenodf/ejerciciospython | /Ejercicios Métodos Cadenas/MetodoIsdigit.py | 225 | 3.671875 | 4 | # Retorna True o False
cadena = "pepegrillo 75" # False
print(cadena.isdigit())
cadena = "7584" # True
print(cadena.isdigit())
cadena = "75 84" # False
print(cadena.isdigit())
cadena = "75.84" # False
print(cadena.isdigit()) |
7eee47209fd1453e85b7cb69bf373529eb64d7ec | rfonseca985/BlueEdTech-modulo1 | /aula_12/exercicio1_aula12.py | 387 | 3.765625 | 4 | #Crie um dicionário em que suas chaves serão os números 1, 4, 5, 6, 7, e 9
# (que podem ser armazenados em uma lista) e seus valores correspondentes aos quadrados desses números.
#{1: 1, 4: 16, 5: 25, 6: 36, 7: 49, 9: 81}
numeros = {}
numero = [1,4,5,7,9]
for i in range(len(numero)):
n_quadrado = numero[i] * numero[i]
numeros.update({numero[i]:n_quadrado})
print(numeros) |
aa185bdac8bc583f626efdcc016871601c6fd93a | widgetti/solara | /solara/website/pages/api/widget.py | 2,741 | 3.75 | 4 | """
# Component.widget
Create a classic ipywidget from a component.
```python
def widget(self, **kwargs):
...
```
This will create a widget from the component. The widget will be a
subclass of `ipywidgets.VBox` and `ipywidgets.ValueWidget`.
Example
```python
import solara
widget = solara.FileDownload.widget(data="some text data", filename="solara-demo.txt")
```
This is very useful if you are migrating your application from a classic
ipywidget to solara. See [also the ipywidgets tutorial](/docs/tutorial/ipywidgets).
The `ipywidgets.ValueWidget` is used to enable the use of the widget in
interact, or interactive. The `ipywidgets.VBox` is used to enable
nesting of widgets.
All keyword arguments will be passed to the component.
Each argument pair of `on_<name>` and `<name>` will
be added as a trait in the widget.
For example,
```solara
import solara
import ipywidgets as widgets
import random
countries_demo_data = {
"Netherlands": ["Amsterdam", "Rotterdam", "The Hague"],
"Germany": ["Berlin", "Hamburg", "Munich"],
"France": ["Paris", "Marseille", "Lyon"],
}
# this component can be used in a component three, but ...
@solara.component
def LocationSelect(value, on_value, countries=countries_demo_data):
country, city = value
cities = countries.get(country, [])
# reset to None if not in the list of countries
if city not in cities:
city = None
# update the state if we changed/reset city
on_value((country, city))
with solara.Card("Location"):
solara.Select(label="country",
values=list(countries),
value=country,
on_value=lambda country: on_value((country, city)),
)
solara.Select(label="city",
values=cities,
value=city,
on_value=lambda city: on_value((country, city)),
)
# Using .widget(...) we can create a widget from it.
# For use with interact:
@widgets.interact(location=LocationSelect.widget(value=("Netherlands", "Amsterdam")))
def f(size=3.4, location=None):
print(size, location)
# Or to add to your VBox:
widgets.VBox(
[LocationSelect.widget(value=("Netherlands", "Amsterdam"))]
)
# this is how you'd use it as a component
@solara.component
def Page():
value, set_value = solara.use_state(("Netherlands", "Amsterdam"))
def pick():
country = random.choice(list(countries_demo_data))
city = random.choice(countries_demo_data[country])
set_value((country, city))
LocationSelect(value=value, on_value=set_value)
solara.Button("Pick random place", on_click=pick)
```
"""
from . import NoPage
Page = NoPage
title = "widget"
|
c1ebcc44325caacd90b8c5388f5d5fb86824009b | dschlimovich/proyectofinal | /Experimentos/DAMIAN/PruebaFuncionesyParametrosporconsola.py | 432 | 3.59375 | 4 | import sys
nom=sys.argv[1]
Ape=sys.argv[2]
MuchasBoludeces=[]
if len(sys.argv) > 3:
for i in range(3,len(sys.argv)):
MuchasBoludeces.append(sys.argv[i])
def funcionPrueba(Nombre,Apellido,MuchasBoludeces):
print(Nombre)
print(Nombre + Apellido)
if len(MuchasBoludeces) >0:
for i in range(0,len(MuchasBoludeces)):
print(MuchasBoludeces[i])
funcionPrueba(nom,Ape)
|
7be6452ec7c96ae421cba018b3ff03a01535a774 | daniel-reich/ubiquitous-fiesta | /aiD5rAhqGLzefNCm9_8.py | 762 | 3.640625 | 4 |
from random import randint
def is_prime(num):
if num < 2:
return False
for p in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
167, 173, 179, 181, 191, 193, 197, 199,]:
if num % p == 0:
return False
rrange, bbreak = 0, num-1
while bbreak % 2 == 0:
rrange, bbreak = rrange+1, bbreak//2
for i in range(100):
res = pow(randint(2, num-1), bbreak, num)
if res == 1 or res == num-1:
for i in range(1, rrange):
res = res**2 % num
if res == 1:
return False
if res == num-1:
break
else: return False
return True
|
641e4d9b99699d12b0f47ff9aa80288344db0d0e | moaazelsayed1/CS50x-psets | /week_6/lec_notes/positive.py | 257 | 3.75 | 4 | from cs50 import get_int
def main():
i = get_positive_nom()
print(i)
def get_positive_nom():
while True:
x = get_int("Enter a positive number: ")
if x > 0:
break
return x
main()
|
b602cd2109903a74006204417d4053021f09bd43 | skyzo123/python | /2020级python所有程序练习/小例子:照猫画虎.py | 472 | 4.125 | 4 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print("hello world!")
hello world!
>>> print('hello world!')
hello world!
>>> x=2
>>> y=1
>>> print(x*x+y*y)
5
>>> def fun():
return x*x+y*y
>>> fun()
5
>>> def fun(x,y):
return x*x+y*y
>>> fun(2,1)
5
>>> for i in range(1,5)
SyntaxError: invalid syntax
>>> for i in range(1,5):
print(i)
1
2
3
4
>>>
|
b272f6d4f8f81481adc9229d12d4505b5ced3922 | nopasanadamindy/Algorithms | /0210/play.py | 2,769 | 4.0625 | 4 | ### 1. Reverse하기
s = "Reverse this strings"
def rev(ary):
l = list(ary)
result = []
for i in range(len(l))[::-1]:
result.append(i)
return ''.join(result)
ary = 'algorithm'
print(rev(ary))
#
# def rev(ary):
# str = list(ary)
# for i in range(len(str)//2):
# str[i], str[len(ary) - 1 - i] = str[len(ary) -1 - i], str[i]
# return ''.join(str)
#
# ary = 'algorithm'
# print(rev(ary))
#
# s = 'Reverse this strings'
# print(s[::-1])
# ###리스트에 안넣어도 되뉴
### 2. <연습문제 2> str함수 쓰지 않고 itoa()구현/ 흐름을 파악하는 것이 중요
# def itoa(x):
# result = []
# str_result = ''
# while x // 10 != 0:
# r = x % 10
# result.append(r)
# x = x // 10
# print(result)
# for i in result:
# str_result += str(i)
# return str_result
# x = 123
# print(itoa(x))
# 선생님 solution
# def itoa(x):
# str = list()
# y = 0
#
# while True::
# y = x % 10
# str.append(chr(y + ord('0')))
# x // = 10
# # if x == 0 : break # while은
#
# str.reverse()
# str = "".join(str)
# return str
# x = 123
# print(itoa(x))
### 3. <연습문제 3>
## 1) 고지식한 방법 : for문
# def bruteF(text, pat):
# for i in range(len(text) - len(pat) + 1):
# for j in range(len(pat)):
# if text[i + j] != pat[j]:
# break
# else:
# return i
#
#
# def bruteF(t, p):
# for i in range(len(t) - len(p) + 1):
# cnt = 0
# for j in range(len(p)):
# if t[i + j] != p[j]:
# break
# else:
# cnt += 1
#
# if len(p) == cnt:
# return i
# text = "TTTAACCA"
# pattern = "TTA"
# print("{}".format(bruteForce(text, pattern)))
# ## 2) 고지식한 방법 : while 문
### ver1)
# def bruteforce(text, pattern):
# # i = 0 # text의 idx
# # j = 0 # pattern의 idx
# # while i < len(text) and j < len(pattern):
# # if text[i] != pattern[j]:
# # i = i - j
# # j = -1
# # else:
# # i = i + 1
# # j = j + 1
# #
# # if j == len(pattern):
# # return i
# # else:
# # return -1
### ver2)
# def bruteforce(text, pattern):
# i = 0 # text의 idx
# j = 0 # pattern의 idx
# while j < len(pattern) and i < len(text):
# if text[i] != pattern[j]:
# i = i - j
# j = -1
# i = i + 1
# j = j + 1
#
# if j == len(pattern):
# return i
# else: return -1
# text = 'This is book'
# pattern = 'is'
# print("{}".format(bruteFore(text, pattern))
# print(text.find(pattern))
### problem |
bc79e07c6a17ecd5a447951be39ea99a458c43c4 | sashaobucina/interview_prep | /python/medium/decode_string.py | 1,278 | 3.953125 | 4 | def decode_string(s: str) -> str:
"""
# 394: The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets
is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are
well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits
are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
"""
stk = []
curr_num, curr_str = 0, ""
for ch in s:
if ch == "[":
stk.append((curr_num, curr_str))
curr_num, curr_str = 0, ""
elif ch == "]":
num, prev_str = stk.pop()
curr_str = prev_str + (num * curr_str)
elif ch.isdigit():
curr_num *= 10
curr_num += int(ch)
else:
curr_str += ch
return curr_str
if __name__ == "__main__":
assert decode_string("3[a]2[bc]") == "aaabcbc"
assert decode_string("3[a2[c]]") == "accaccacc"
assert decode_string("2[abc]3[cd]ef") == "abcabccdcdcdef"
assert decode_string("abc3[cd]xyz") == "abccdcdcdxyz"
print("Passed all tests!")
|
09c32b6c72b7f37bd85bf0553c64fca4bc206832 | adithyanps/Think_python | /practice/ex17.4.py | 159 | 3.890625 | 4 | class Point(object):
def __init__(self, x=None):
self.x = x
def __add__(self, other):
return self.x + other.x
p1 = Point(5)
p2 = Point(-3)
print p1 + p2
|
694ae0b62653d83bfa22a0883375dd0a02384ffd | liuxinqiqi/Pythonself | /others/intr.py | 859 | 4.03125 | 4 | #coding=utf-8
#自省机制函数
#hasattr getattr setattr delattr
#isinstance(判断某个对象是否是该类的对象)
#issubclass(判断一个类是否继承另一个类)
class Parent(object):
name = 'liu'
class Child(Parent):
pass
p = Child()
print issubclass(Child,Parent) #判断第一个类是否由第二个类创建
print isinstance(p,Parent) #判断对象p是否属于Parent类
print "======================="
print hasattr(p,'name') #获取name的值
l = []
print hasattr(l,'append') #append为内建函数,hasattr是判断是否存在
print getattr(p,'name') #getattr是获取类内的属性变量
setattr(p,'age',23)
print p.age
delattr(p,'age') #可以删除age,以为age是由变量p自定义的变量
# delattr(p,'name') #不可删除name,因为name是属于类里的属性变量
|
09737beddc590a085adcf995bb16966e326d0d82 | M1K43L4/CodeWars | /Ten_Minute_Walk.py | 632 | 3.953125 | 4 | def is_valid_walk(walk):
coord_x = 0
coord_y = 0
time = 0
directions = ['n', 's', 'e', 'w']
for char in walk:
if char in directions:
time += 1
if char == 'n':
coord_y += 1
elif char == 's':
coord_y -= 1
elif char == 'e':
coord_x += 1
else:
coord_x -= 1
if time == 10 and coord_x == 0 and coord_y == 0:
return True
else:
return False
if __name__ == '__main__':
print(is_valid_walk(['n','n','n','s','n','s','n','s','n','s']))
|
b1dd712b00f4714eefe62630e1fb6e46da3cdbda | yiyada77/algorithm | /Python/86-partition.py | 609 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def partition(self, head: ListNode, x: int) -> ListNode:
if not head or not head.next:
return head
small = small_head = ListNode()
big = big_head = ListNode()
while head:
if head.val < x:
small.next = head
small = small.next
else:
big.next = head
big = big.next
head = head.next
small.next = big_head.next
big.next = None
return small_head.next
|
f457c9070b7ef2c104134c5bb08c9f4a429912af | AdamZhouSE/pythonHomework | /Code/CodeRecords/2893/39200/304235.py | 188 | 3.640625 | 4 | sum = input()[1:-1].split(",")
sum.sort()
x = 0
while x < len(sum):
if x == len(sum)-1:
print(sum[x])
if sum[x] == sum[x+1]:
x += 3
else:
print(sum[x])
|
4b3a11bdc263dd21123f0fda173a7fef6d432f90 | hoodielive/modernpy | /2020/archive/exercise01.py | 284 | 3.59375 | 4 | import typing
a = ('apple', 1, 'Amber', 2.5)
fruit, integer, sister, afloater = a
print(fruit)
print(integer)
print(sister)
print(afloater)
print(a)
b = ()
class Stock(typing.NamedTuple):
name: str
shares: int
price: float
stock = Stock(3, 100, 490.1)
print(stock)
|
9b672366b2fed163f054835065e9ca003ba5b3b5 | zpazylbe/coding_challenges | /ten_pin_bowling.py | 2,162 | 3.640625 | 4 | def bowlingScore(frames):
"""Ten-Pin Bowling.
Calculate player's total score given a string represeting a player's ten frames
Description: https://www.codewars.com/kata/5531abe4855bcc8d1f00004c
Parameters:
frames (str): player's ten frames
Returns:
int: player's final score
"""
# Convert the input string to a list. Convert numeric score into integers.
frames_list = list(frames)
frames_list = [x for x in frames_list if x != ' ']
frames_list = [int(ele) if ele.isdigit() else ele for ele in frames_list]
# score_list will represent the numeric scores of the 10 frames
score_list = frames_list
# Keep the strike and spares indices in separate lists.
strikes_indices = []
spares_indices = []
# Keep scores for strikes and spares
total_strike_score = 0
total_spares_score = 0
# Keep track of frames count
frames_count = 0
for pos, elem in enumerate(frames_list, start=0):
# Strike scoring
if elem == 'X':
score_list[pos] = 10
# Keep track of strike indices except the last frame
if frames_count < 9:
strikes_indices.append(pos)
# Strike counts as 1 full frame
frames_count = frames_count + 1
elif elem == '/':
score_list[pos] = 10 - score_list[pos - 1]
# Keep track of spares indices except the last one
if frames_count < 9:
spares_indices.append(pos)
# Strike counts as a half of a frame
frames_count = frames_count + 0.5
else:
# Counts as a half of a frame
frames_count = frames_count + 0.5
# Calculate total strike score
for j in strikes_indices:
strike_score = score_list[j + 1] + score_list[j + 2]
total_strike_score = total_strike_score + strike_score
# Calcualte spares score
for j in spares_indices:
spare_score = score_list[j + 1]
total_spares_score = total_spares_score + spare_score
total_score = total_strike_score + total_spares_score + sum(score_list)
return total_score |
de5dc80c2238b879b021479bb1f507214025374e | Abdulrahman-Adel/Data-structures-and-Algorithms-Udacity-ND | /Maps and Hashing/Caching.py | 806 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Problem Statement
A child is running up a staircase with and can hop either 1 step, 2 steps or 3 steps at a time.
If the staircase has n steps,
write a function to count the number of possible ways in which child can run up the stairs.
"""
import functools
"""
this is a cashe which creates a thin wrapper around a dictionary lookup
for the function arguments. Because it never needs to evict old values.
"""
@functools.lru_cache(maxsize=None)
def staircase(n):
if n == 0:
return 1
elif n < 0:
return 0
else:
climb_ways = 0
climb_ways += staircase(n - 1)
climb_ways += staircase(n - 2)
climb_ways += staircase(n - 3)
return climb_ways
print(staircase(5)) |
eb0160e2e07377c0299469dbe24fc51fd922857e | sheleh/homeworks | /lesson4/task_4_1.py | 529 | 4.15625 | 4 | #The Guessing Game.
#Write a program that generates a random number between 1 and 10
# and lets the user guess what number was generated.
# The result should be sent back to the user via a print statement.
import random
status = False
while not status:
user_choice = int(input('lets try to guess a number between 1 and 10: '))
random_number = random.randint(1,10)
if user_choice == random_number:
print(f'Got it!!! {user_choice} is right choice')
break
else:
print('Nope, lets try again') |
01f847ce50453b3b8aee6828389ca082484fb542 | amisha1garg/Arrays_In_Python | /BalancedArray.py | 1,068 | 3.90625 | 4 | # Given an array of even size N, task is to find minimum value that can be added to an element so that array become balanced. An array is balanced if the sum of the left half of the array elements is equal to the sum of right half.
#
#
# Example 1:
#
# Input:
# N = 4
# arr[] = {1, 5, 3, 2}
# Output: 1
# Explanation:
# Sum of first 2 elements is 1 + 5 = 6,
# Sum of last 2 elements is 3 + 2 = 5,
# To make the array balanced you can add 1.
#User function Template for python3
class Solution:
def minValueToBalance(self,a,n):
#code here.
s=0
x=0
for i in range(0,(int(n/2))):
s= s+a[i]
for j in range(int(n/2),n):
x += a[j]
if s==x:
return 0
else:
return abs(s-x)
#{
# Driver Code Starts
#Initial Template for Python 3
t=int(input())
for _ in range(0,t):
n=int(input())
a = list(map(int,input().split()))
ob = Solution()
ans=ob.minValueToBalance(a,n)
print(ans)
# } Driver Code Ends |
abd94405f3383517500dc2e39d5c049810bec706 | viralbaitule/DSA-Python | /Cracking the coding Interview/Arrays and strings/Q1_3.py | 624 | 3.8125 | 4 |
def permute_and_check(s1,s2,l,r,check):
if (l==r):
print (s1)
if s1==s2:
check="True"
else:
for i in range(l,r+1):
s1[l],s1[i]=s1[i],s1[l]
check=permute_and_check(s1,s2,l+1,r,check)
s1[l],s1[i]=s1[i],s1[l]
return check
def check_permutation(s1,s2):
if len(s1)!=len(s2):
return False
s1=list(s1)
s2=list(s2)
return(permute_and_check(s1,s2,0,len(s1)-1,"False"))
def check_permuatation_sorting(s1,s2):
s1=list(s1)
s2=list(s2)
s1.sort()
s2.sort()
return s1==s2
s1="dog"
s2="god"
print(check_permutation(s1,s2))
print ("using sorting alorithm")
print (check_permuatation_sorting(s1,s2)) |
a2a76fc54de1b05df4f322501799fab9d0d44ab2 | alexander-braun/python-basic | /classes_and_objects_usage.py | 206 | 3.5625 | 4 | from classes_and_objects import Student
# create student1 from Student class
student1 = Student("Dieter", "Electronics", 3.1, False)
print(student1.name)
# call method from class
student1.sayStudentName() |
6ef4dc04e78421f07290320612039597211a2358 | mmad26/Tareas_Greencore | /Tarea2/Ejercicio1 - NumeroMayor.py | 413 | 4.0625 | 4 | uno = int(input("Digite un numero: "))
dos = int(input("Digite otro numero: "))
tres = int(input("Digite un ultimo numero: "))
def numero_mas_alto(uno, dos, tres):
mayor = 0
if uno > dos and uno > tres:
mayor = uno
elif dos > uno and dos > tres:
mayor = dos
else:
mayor = tres
return mayor
print(numero_mas_alto(uno, dos, tres), "es el numero mas alto de los tres.") |
2c58582181926b157faafc0aa94a6238148f1c6a | adityaaggarwal19/data-structures-MCA-201 | /trial.py | 1,775 | 3.546875 | 4 | from Record import Record
from createfile import *
from tryy import *
if __name__=="__main__":
b = None
while True:
print("**************************** B+ TREE *********************************")
print("1. Create record file")
print("2. Create index file")
print("3. Print whole index file")
print("4. Search for a record")
print("5. Exit")
try:
ch=int(input("\n Enter your choice:"))
except ValueError:
print("Invalid choice")
break
if ch == 1:
createFile(int(input("Enter the number of records you want to create:")))
print("Record file and position file created..")
elif ch == 2:
n = int(input("Enter the number of records you want to add in B+ tree:"))
b = BPlus()
f1 = open('Data','rb')
for i in range(n):
obj = pickle.load(f1)
print("Inserting Key:",obj.getKey())
b.insertRecord(obj)
f1.close()
f2 = open('IndexPos.txt','wb')
pickle.dump(b.nodeAddress,f2)
f2.close()
print("Index file and index position file created..")
elif ch == 3:
f1 = open('indexfile.txt','rb')
n = 0
for i in b.nodeAddress:
print("\nNODE "+ str(n)+":")
f1.seek(i)
r = pickle.load(f1)
print(r)
n += 1
elif ch == 4:
n = int(input('Enter the key:'))
search(n)
else:
break
|
3cef0efb6181f5745f723b7241b5d4ecd232669e | Air-Zhuang/Test35 | /oop/ABC/abc1.py | 1,904 | 3.96875 | 4 | from abc import ABC, abstractmethod #注意这里是abc模块下的ABC,不是collections模块下的abc
'''
类似于java中的抽象接口,只要继承的父类有抽象方法,必须实现(尽量不要使用,可以用python的鸭子类型来代替)
1、我们需要强制某个子类必须实现某些方法
2、我们某些情况下希望判定某个对象的类型
'''
'''abc.ABC是Python3.4新增的类。
从python3.0到3.3,必须在class语句中使用metaclass=ABCMeta: class Tombola(metaclass=ABCMeta):
python2: class Tombola(object):
__metaclass__=abc.ABCMeta
'''
'''声明抽象类方法的推荐方法是:
class MyABC(abc.ABC):
@classmethod
@abstractmethod
def an_abstract_classmethod(cls, ...):
pass
'''
'''1、我们需要强制某个子类必须实现某些方法'''
class A(ABC):
@abstractmethod
def ppp(self):
pass
class B(A):
def ppp(self):
print("This is B") #子类必须实现父类的抽象方法
class C(A):
def fool(self):
print("I'm fool!")
def ppp(self):
print("This is C")
b = B()
b.ppp()
c = C()
c.fool()
c.ppp()
print()
class A:
def ppp(self):
raise NotImplementedError #可以用Python的鸭子类型代替抽象基类的实现
class B(A):
def ppp(self):
print("This is B")
class C(A):
def fool(self):
print("I'm fool!")
def ppp(self):
print("This is C")
b = B()
b.ppp()
c = C()
c.fool()
c.ppp()
print()
'''2、我们某些情况下希望判定某个对象的类型'''
from collections.abc import Sized
class Company:
def __init__(self,employee_list):
self.employee=employee_list
def __len__(self):
return len(self.employee)
com=Company(["air1","air2"])
print(hasattr(com,"__len__")) #传统判定
print(isinstance(com,Sized)) #通过抽象基类判定 |
1ed9af1838420bea6d8682d10c71b0fc438a4550 | billy1479/python | /sorting.py | 535 | 3.625 | 4 | list1 = [34,56,34,26,80,57,98,100,80,64,102,300,35,6,87,88]
count = 0
for x in range(0,len(list1)):
if list1[x] >= 80 and list1[x] <=100:
print(list1[x])
count = count + 1
print("integers in list are " + str(count))
values = []
for i in range(0, len(list1)):
if list1[i] >= 80 and list1[i] <=100:
values.append(list1[i])
print("")
for y in range(0, len(values)):
try:
print(values[y])
list1.remove(values[y])
except ValueError:
pass
print(list1)
|
6db9460ef6b79fc97de832e47bc131c7492fb664 | congyingTech/Basic-Algorithm | /getOffer/45.circle-last-num.py | 1,074 | 3.84375 | 4 | # encoding:utf-8
"""
问题描述:
0~n-1排成一个圆圈,从数字0开始删除圆圈里的第m个数字,求圆圈中最后剩下的数字。
解决方案:
循环链表删除操作
"""
class CircleNode(object):
def __init__(self, val):
self.val = val
self.next = None
class Solution(object):
def findCircleLastNum(self, circle, m):
res = []
p1 = circle
while p1 and p1.next!=p1:
time = m
while time>1:
p1=p1.next
time -= 1
res.append(p1.val)
# 将后一个结点的值赋给p1,然后删除后一个结点
temp = p1.next.val
p1.val = temp
p1.next = p1.next.next
print(res)
print(p1.val)
if __name__ == "__main__":
s = Solution()
t1 = CircleNode(1)
t2 = CircleNode(2)
t3 = CircleNode(3)
t4 = CircleNode(4)
t5 = CircleNode(5)
t1.next = t2
t2.next = t3
t3.next = t4
t4.next = t5
t5.next = t1
m = 3
s.findCircleLastNum(t1, m) |
66d6e7c4af4d0abb30985214b2d51a97821bdfee | arunsambargi/euler | /python6.py | 1,043 | 3.734375 | 4 | # Problem Header :Sum square difference
"""
Problem Description:
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
"""
def euler6(istart,iend):
if istart == 0 or iend == 0 or istart == iend:
return 0
if istart > iend :
istart,iend = iend,istart
a = 0
b = 0
for i in range(istart,iend+1):
b = b + i**2
a = a + i
a = a**2
print('The first number is %d' % a)
print('The second number is %d' % b)
return (a - b)
inps = int(input('Enter the Start Range : '))
inpe = int(input('Enter the End Range : '))
print('The result is %d' % euler6(inps,inpe))
if __name__ == '__main__':
import timeit
print(timeit.timeit(stmt="euler6(%d,%d)" % (inps,inpe), number=3, setup="from __main__ import euler6"))
|
64f2c95849e8ceef3f25abc69176c300f6d4bb43 | carlos3dx/hash_code_practice | /components/competition.py | 655 | 3.546875 | 4 | class Competition:
def __init__(self, teams_of_two: int, teams_of_three: int, teams_of_four: int) -> None:
self.teams_of_two = teams_of_two
self.teams_of_three = teams_of_three
self.teams_of_four = teams_of_four
self.total_teams = teams_of_two + teams_of_three + teams_of_four
self.total_people = teams_of_two * 2 + teams_of_three * 3 + teams_of_four * 4
def __eq__(self, other):
return isinstance(other, Competition) and \
self.teams_of_two == other.teams_of_two and \
self.teams_of_three == other.teams_of_three and \
self.teams_of_four == other.teams_of_four
|
388bc636589a12c156d618fd8db1b8f02dbd2fd5 | edu-athensoft/stem1401python_student | /py210110c_python1a/day16_210425/homework/stem1401_0418_homework_yiding.py | 849 | 3.859375 | 4 | """
[Homework] of Yiding
Date: 2021-04-18
Quiz 6 q1-q6
Due date: by the end of next Sat.
"""
"""
q1.
standard input device:
mic
standard output device:
screen
q2.
Input devices:
keyboard, webcam
Output device:
scanner, printer
q3.
print('something')
input()
print('===done===')
q4.
print('something')
print(input('write down something:'))
print('===done===')
q5.
-they can input as many as they want
- string
q6.
print('===Login===')
username = input ('Please enter your username ')
password = input('Please enter your password:')
print("Welcome back, ", username, "!")
print()
print("=== Done, ===")
"""
"""Test"""
print("=== Login Form ===")
username = input('Please enter your username:')
password = input('Please enter your password:')
number = input('Please enter your number:')
print("Hi, ", username, ":)")
print("=== Done ===")
|
23ca5fdf576ecc7704ea815d876cb70667486e87 | Pratik2711/Machine-Learning | /que16.py | 204 | 3.875 | 4 | #16. Given a 1D array, negate all elements which are between 3 and 8, in place.
import numpy as np
arr=np.arange(0,9)
a= (arr>3) & (arr<8)
arr[a]*=-1
print(arr)
'''OUTPUT:
[ 0 1 2 3 -4 -5 -6 -7 8]''' |
1478913800556d0fc14d4a190031d22537ce852e | Frankiee/leetcode | /bitwise/single_number/260_single_number_iii.py | 1,041 | 3.828125 | 4 | # [Classic, XOR]
# https://leetcode.com/problems/single-number-iii/
# 260. Single Number III
# Given an array of numbers nums, in which exactly two elements appear only
# once and all the other elements appear exactly twice. Find the two
# elements that appear only once.
#
# Example:
#
# Input: [1,2,1,3,2,5]
# Output: [3,5]
# Note:
#
# The order of the result is not important. So in the above example, [5,
# 3] is also correct.
# Your algorithm should run in linear runtime complexity. Could you
# implement it using only constant space complexity?
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
xor = 0
for n in nums:
xor ^= n
# mask to partition the a and b into two groups
mask = 1
while xor & mask == 0:
mask <<= 1
a = b = 0
for n in nums:
if mask & n == 0:
a ^= n
else:
b ^= n
return [a, b]
|
4cd4230ab998aeae6ecc5edcc8ff8b8e4872fc40 | ymilkessa/ch-games | /game_state.py | 4,897 | 3.625 | 4 | from constants import BLACK, WHITE
from copy import deepcopy
import random
class GameState():
def __init__(self, board, side, players):
self._players = players
self._turn_counter = 1
# read only properties
self._current_side = side
self._board = board
# public property
self._draw_counter = 0
@property
def current_side(self):
return self._current_side
@property
def board(self):
return self._board
@property
def draw_counter(self):
return self._draw_counter
@draw_counter.setter
def draw_counter(self, c):
self._draw_counter = c
def next_turn(self):
self._current_side = not self._current_side
self._turn_counter += 1
def prev_turn(self):
self._current_side = not self._current_side
self._turn_counter -= 1
def __str__(self):
if self._current_side == WHITE:
side_string = "white"
elif self._current_side == BLACK:
side_string = "black"
else:
raise ValueError("Current player is neither black nor white")
return f"{self._board}\nTurn: {self._turn_counter}, {side_string}"
def all_possible_moves(self, side=None):
"""Iterates over a side's pieces and returns a list containing all legal moves
Args:
side ([type], optional): side for which moves should be retrieved. Defaults to the game state's current side.
Returns:
list: list of Move objects
"""
if not side:
side = self._current_side
pieces = self._board.pieces_iterator(side)
options = []
for piece in pieces:
options.extend(piece.enumerate_moves())
return options
def get_optimal_move(self, depth, best_so_far=-1000, side=None):
"""Applies the minimax algorith to recursively compute the expected gain/loss total of making a move.
Args:
depth (int): how many steps of recursion you want to make
side (bool, optional): Default gets replaced by the current side, either WHITE or BLACK
best_so_far (int): The best utility from neighboring branches; for alpha-beta pruning
Return:
tuple([optimal_move, expected_value]): optimal_move is a Move instance; expected_value is an int
"""
if side == None:
side = self._current_side
next_moves = self.all_possible_moves(side) # This cannot be [] at this point
options_list = []
for poss_m in next_moves: # poss_m means 'possible_move'
current_utility = poss_m.val_of_captures()
if depth == 0:
new_option = (poss_m, current_utility)
else:
state_copy = deepcopy(self)
move_copy = poss_m.copy_from(state_copy)
move_copy.execute(state_copy)
# Now you're in the oponent's shoes. First check if the game is over already
if self.check_loss() or self.check_draw():
opponent_move = [None, 0]
else:
opponent_move = state_copy.get_optimal_move(depth-1, best_so_far)
new_option = (poss_m, current_utility-opponent_move[1])
# Do the alpha-beta pruing
if new_option[1] > best_so_far:
best_so_far = new_option[1]
elif new_option[1] < best_so_far:
# break the loop here
options_list = [new_option]
break
options_list.append(new_option)
# debugging block
if not options_list:
breakpoint()
# Now pick the option with the highest utility
best_option = options_list[0]
for next_option in options_list[1:]:
if next_option[1] > best_option[1]:
best_option = next_option
elif next_option[1] == best_option[1]:
best_option = random.choice([next_option, best_option])
return (best_option[0].copy_from(self), best_option[1])
def check_draw(self, side=None):
if not side:
side = self._current_side
# no moves available
if len(self.all_possible_moves(side)) == 0:
return True
# 50 turn rule
if self._draw_counter >= 50:
return True
# default to no draw
return False
def check_loss(self, side=None):
# Specific rules for loss should be implemented per game
raise NotImplementedError()
def get_space(self, space):
return self.board.get_space_from_coords((space.row, space.col))
|
146578845d16a58a647ad315a709ccfba973ed08 | CguarinoNJIT/CalculatorProgram | /Calculator/Calculator.py | 945 | 3.625 | 4 | from Calculator.Addition import addition
from Calculator.Subtraction import subtraction
from Calculator.Multiplication import multiplication
from Calculator.Division import division
from Calculator.SquareRoot import squareroot
from Calculator.Square import square
__all__ = ['Calculator']
class Calculator:
result = 0
def __init__(self):
pass
def add(self,a,b):
self.result = addition(a,b)
return self.result
def subtract(self,a,b):
self.result = subtraction(a,b)
return self.result
def multiply(self,a,b):
self.result = multiplication(a,b)
return self.result
def divide(self,a,b):
self.result = division(a,b)
return self.result
def square_root(self,a, decimal_places=8):
self.result = squareroot(a, decimal_places)
return self.result
def squared(self,a):
self.result = square(a)
return self.result
|
8b07e762911b39a6c68a8223ff9c0e51aaefb8ae | guziy/RPN | /src/util/number_formatting.py | 1,080 | 4 | 4 | __author__ = 'huziy'
def ordinal(value):
"""
Source: http://code.activestate.com/recipes/576888-format-a-number-as-an-ordinal/
Modified it a bit for python3....
Converts zero or a *postive* integer (or their string
representations) to an ordinal value.
>>> for i in range(1, 13):
... ordinal(i)
'1st'
'2nd'
'3rd'
'4th'
'5th'
'6th'
'7th'
'8th'
'9th'
'10th'
'11th'
'12th'
>>> for i in (100, '111', '112', 1011):
... ordinal(i)
...
'100th'
'111th'
'112th'
'1011th'
"""
try:
value = int(value)
except ValueError:
return value
if value % 100 // 10 != 1:
if value % 10 == 1:
suffix = "st"
elif value % 10 == 2:
suffix = "nd"
elif value % 10 == 3:
suffix = "rd"
else:
suffix = "th"
else:
suffix = "th"
ordval = "{}{}".format(value, suffix)
return ordval
if __name__ == '__main__':
for i in range(1, 13):
print(ordinal(i)) |
6cb587426e7019f543fb1860d81584191d810c72 | idane19-meet/meet2017y1lab3 | /ages.py | 163 | 3.984375 | 4 | age1 = int(input('what is your age: '))
age2 = int(input('what is your age other person: '))
print('Did you know?!?the sum of your ages is ' + str(age1 + age2))
|
3655287834d04a362ea94bfd45a781d812c75ccf | jiangjiangzhijia/python | /20160817/02.py | 634 | 4.21875 | 4 | #1
#name = raw_input("what's your name : ")
#print 'hello,'+name
#2
#print 'let\'s go'
#print repr('hello world')
#print str('hello world')
#print `hello world`
#3
#temp = 42
#print "the Temperature is " + `temp`
#print "the Temperature is " + repr(temp)
#print "the Temperature is " + str(temp)
#4
#name = raw_input("What's your name?")
#print 'Hello. ' + name + "!"
#5
#print '''asdfsadfasdfasdfasdfasdfasdfasdfasdfsadfsadfasdfsdjasdjfklsjdfkjsdfkljdskfjksdfjkjfkjsdkfjksdfjkdjfskjfkdsjf
#sdfsdfsadfsdf'''
#6
#print r"hello,world" '\\'
#7
#print u'Hello,world'
help()
raw_input("Press <enter>")
|
8bcf9e038ff3851bb189eb4f6433f0e9ee6f4dcc | ColeRichardson/grade_calculator | /course.py | 736 | 3.78125 | 4 | from assignment import Assignment
class Course:
def __init__(self):
self.gradeList = []
def addGrade(self, gr):
self.gradeList.append(gr)
def getWeightedAverage(self):
"""
>>> x = grade("quiz1", 0.1, 50)
>>> y = grade("quiz2", 0.1, 60)
>>> CSC258 = Course()
>>> CSC258.addGrade(x)
>>> CSC258.addGrade(y)
>>> CSC258.getWeightedAverage()
"""
sum1 = 0
weightsum = 0
for i in self.gradeList:
if (i.mark != None ):
weightsum += i.getWeight()
sum1 += i.getWeight() * i.getMark()
return (sum1 / weightsum , weightsum)
x = Assignment("quiz1", 0.1)
y = Assignment("quiz2", 0.1)
x.setMark(50)
y.setMark(60)
CSC158=Course()
CSC158.addGrade(x)
CSC158.addGrade(y)
print(CSC158.getWeightedAverage())
|
3e3a4623a6cd51021b437d1db4a75220de497c3b | Atsunori66/garage | /wordle.py | 723 | 3.546875 | 4 | guess = input('enter: ')
answer = 'world'
if guess[0] in answer:
if guess[0] == answer[0]:
print(guess[0], ': hit')
else:
print(guess[0], ': blow')
if guess[1] in answer:
if guess[1] == answer[1]:
print(guess[1], ': hit')
else:
print(guess[1], ': blow')
if guess[2] in answer:
if guess[2] == answer[2]:
print(guess[2], ': hit')
else:
print(guess[2], ': blow')
if guess[3] in answer:
if guess[3] == answer[3]:
print(guess[3], ': hit')
else:
print(guess[3], ': blow')
if guess[4] in answer:
if guess[4] == answer[4]:
print(guess[4], ': hit')
else:
print(guess[4], ': blow')
|
7ee62fe7a13da3e27c333fdf415bc3b170d58eda | divyagupta2410/exception_handling | /exception handelling assignment.py | 319 | 3.625 | 4 | #1.
def funct():
try:
d=5/0
print(d)
except Exception as e:
print("",e)
funct()
#2.
subjects=["Americans","Indians"]
verbs=["play","watch"]
objects=["Baseball","Cricket"]
x=[s+" "+v+" "+o+"." for s in subjects for v in verbs for o in objects]
for i in x:
print(i)
|
78497860c800a4131424e4a47fd8f3bedbc26867 | fmorenovr/ComputerScience_UNI | /CM334-Analisis_Numerico_I/systemLinearEquations/nxm_Systems_LE/dscmpQRMthds/auxFuncSLE.py | 17,705 | 3.96875 | 4 | #!/usr/bin/env python
"""Definiciones:
A, M : Matriz original.
a : Matriz aumentada (A|b)
b : Vector independiente.
L : Matriz triangular inferior unitaria.
M : Matriz triangular inferior unitaria.
U : Matriz triangular superior unitaria.
D : Matriz diagonal.
P : Matriz de permutacion
Pr : Matriz de permutacion de filas
Pc : Matriz de permutacion de columnas
G : Matriz superior hallada con el metodo de Cholesky.
Gt : Transpuesta de G.
A = LU : significa factorizacion sin pivoteo
PA = LU : significa factorizacion con pivoteo parcial
PAQ = LU : significa factorizacion con pivoteo total
piv: pivoteo, piv=0 sin pivoteo, piv=1 con pivoteo parcial piv=2 con pivoteo total
"""
from math import *
from sys import exit
# ------------------------------------------------------------
# Ingresar datos a una matrix
def inputMatrix():
print("Ingreso de datos de la matriz")
done=0
while not done:
m = raw_input("Ingrese el orden de la matriz: ")
if m=='':
print("vuelva a ingresar")
else:
n=int(m)
print("Ingrese los elementos de la matriz A fila por fila con un espacio luego enter")
A = [[0.0]*n for i in range(n)]
aux = [[0.0]*n for i in range(n)]
for i in range(n):
temp = raw_input()
A[i] = temp.split()
for j in range(n):
A[i][j] = float(A[i][j])
if A == aux:
exit('Matriz nula, vuelva a escribir la matriz')
else:
done=1
return A
# ------------------------------------------------------------
# ingresar datos a un vector
def inputVector():
print("Ingreso de datos del vector")
done=0
while not done:
m = raw_input("Ingrese la dimension del vector b: ")
if m=='':
print("vuelva a ingresar")
else:
n = int(m)
b = [0.0]*n
temp = raw_input()
b = temp.split()
for i in range(n):
b[i] = float(b[i])
done=1
return b
# ------------------------------------------------------------
# imprime matrix con indices
def printMatrixIndex(M):
for i in range(len(M)):
for j in range(len(M[i])):
if(i == 0 and j == 0):
print " "
for x in range(len(M[i])):
print '{0:8}'.format(x),
print("")
if(j == 0):
print i,
print '{0:8.4f}'.format(M[i][j]),
print '|'
print
# ------------------------------------------------------------
# imprime matrix sin indices
def printMatrix(M):
for i in range(len(M)):
print '|',
for j in range(len(M[i])):
print '{0:8.4f}'.format(M[i][j]),
print '|'
print
# ------------------------------------------------------------
# Norma 1 de una matriz
def norm1Matrix(A):
summation = 0
for i in range(len(A)):
summation += abs(A[i][0])
for j in range(1, len(A)):
temp = 0
for i in range(len(A[i])):
temp += abs(A[i][j])
summation = temp if (temp > summation) else summation
return summation
# ------------------------------------------------------------
# norma infinita de una matriz
def normInfMatrix(A):
summation = 0
for j in range(len(A)):
summation += abs(A[0][j])
for i in range(1, len(A)):
temp = 0
for j in range(len(A[i])):
temp += abs(A[i][j])
summation = temp if (temp > summation) else summation
return summation
# ------------------------------------------------------------
# norma euclidiana o de fobrenius del vector x, ie, ||x||2
def eucliNorm(x):
return sqrt(sum([x_i*x_i for x_i in x]))
# ------------------------------------------------------------
# Calcula la norma infinita de un vector: ||x|| = max {|xi|}, i = 0, 1, ... n.
def normaInfVector(L):
maximum = fabs(L[0])
for i in range(1, len(L)):
maximum = max(maximum, fabs(L[i]))
return maximum
# ------------------------------------------------------------
# evalua si una matrix es simetrica
def isSymmetricMatrix(A):
# print("Evalua si una matriz es simetrica")
for i in range(len(A)):
for j in range(i+1,len(A)):
if A[i][j] != A[j][i]:
# print("No es simetrica")
return False
# print("Si es simetrica")
return True
# ------------------------------------------------------------
# transpuesta de una matriz
# [M[i][j] for i in range(n)] imprime M[i][j] (j fijo), es decir, imprime A[0][j],A[1][j], ... y con el siguiente igual
# probar [M[i][1] for i in range(n)]
def transMatrix(M):
n = len(M)
m = len(M[0])
return [[ M[i][j] for i in range(n)] for j in range(m)]
# ------------------------------------------------------------
# inversa de una matriz
def invMatrix(D):
n = len(D)
A = [row[:] for row in D]
B = [[float(i == j) for j in range(n)] for i in range(n)]
C = [[0.0]*n for i in range(n)]
# transformacion de la matriz y de los terminos independientes
for k in range(n-1):
for i in range(k+1,n):
# terminos independientes
for s in range(n):
B[i][s] -= A[i][k]*B[k][s]/A[k][k]
# elementos de la matriz
for j in range(k+1,n):
A[i][j] -= A[i][k]*A[k][j]/A[k][k]
# calculo de las incognitas, elementos de la matriz inversa
for s in range(n):
C[n-1][s] = B[n-1][s]/A[n-1][n-1]
for i in range(n-2,-1,-1):
C[i][s] = B[i][s]/A[i][i]
for k in range(n-1,i,-1):
C[i][s] -= A[i][k]*C[k][s]/A[i][i]
return C
# ------------------------------------------------------------
# inversa de una matriz triangular inferior ( menos pasos )
def invMatrixInf(Lower):
n = len(Lower)
L = [ row[:] for row in Lower]
Inv = [ [float(q==w) for q in range(n) ] for w in range(n)]
for i in range(n):
# dividimos la fila i entre L[i][i]
for j in range(0,i+1):
Inv[i][j] = 1.*Inv[i][j]/L[i][i]
L[i][j] = 1.*L[i][j]/L[i][i]
# operamos sobre la fila
for i in range(n):
for j in range(i+1,n):
const = L[j][i]
susRows(L,j,i,const)
susRows(Inv,j,i,const)
return Inv
# ------------------------------------------------------------
# Aumenta una matriz un vector
# Retorna la matriz aumentada
def augmentedMatrixVector(M, b):
A = [row[:] for row in M]
for i in range(len(M)):
A[i].append(b[i])
return A
# ------------------------------------------------------------
# Maximo numero en una columna empezando de la diagonal
def maxColum(M, c):
r = c #fila
maximum = M[c][c]
for i in range(c+1,len(M)):
if(fabs(maximum) < fabs(M[i][c])):
maximum = M[i][c]
r = i
return r
# ------------------------------------------------------------
# Devuelve el mayor en una fila empezando de la diagonal
def maxRow(M, c):
r = c #fila
maximum = M[c][c]
for i in range(c+1,len(M)):
if(fabs(maximum) < fabs(M[c][i])):
maximum = M[c][i]
r = i
return r
# ------------------------------------------------------------
# Maximo numero en una columna empezando debajo la diagonal
def maxColumDiag(M, c):
r = c #fila
maximum = M[c+1][c]
for i in range(c+1,len(M)):
if(fabs(maximum) < fabs(M[i][c])):
maximum = M[i][c]
r = i
return r
# ------------------------------------------------------------
# Devuelve el mayor en una fila empezando derecha la diagonal
def maxRowDiag(M, c):
r = c #fila
maximum = M[c][c+1]
for i in range(c+1,len(M)):
if(fabs(maximum) < fabs(M[c][i])):
maximum = M[c][i]
r = i
return r
# ------------------------------------------------------------
# intercambia las filas r1 y r2 de M
def exchangeRows(A, r1, r2):
M = [row[:] for row in A]
M[r1], M[r2] = M[r2], M[r1]
return M
# ------------------------------------------------------------
# intercambia las columnas c1 y c2 de M
def exchangeCols(A, c1, c2):
M = [row[:] for row in A]
for k in range(len(M)):
M[k][c1] , M[k][c2] = M[k][c2], M[k][c1]
return M
# ------------------------------------------------------------
# Retorna el mayor elemento de la submatriz iniciada desde A[c][c]
def maxSubMatrix(M, c):
row = c
colum = c
n = len(M)
maximum = M[c][c]
for j in range(c, n):
for k in range(c, n):
maxTemp = M[k][j]
if(fabs(maximum) < fabs(maxTemp)):
maximum = maxTemp
colum = j
row = k
return row, colum
# ------------------------------------------------------------
# Privote de cualquier metodo
def pivot(a, P, Q, colum,s=[],piv=0):
done=0
if piv > 3 or piv < 0:
exit('Valores invalidos para el parametro pivoteo, valores validos: 0, 1, 2, 3.')
n = len(a)
temp = a[colum][colum]
if(temp == 0.0 and piv == 0): # sin pivot
row_maxColumn = maxColum(a, colum)
a = pivotP(a, row_maxColumn, colum)
P = exchangeRows(P, row_maxColumn, colum)
#print 'P(%d,%d)' % (row_maxColumn, colum)
#printMatrix(rowsPermutMatrix(n, row_maxColumn, colum))
elif piv == 1: # privoteo parcial
row_maxColumn = maxColum(a, colum)
if row_maxColumn != colum:
a = pivotP(a, row_maxColumn, colum)
P = exchangeRows(P, row_maxColumn, colum)
#print 'P(%d,%d)' % (row_maxColumn, colum)
#printMatrix(rowsPermutMatrix(n, row_maxColumn, colum))
elif piv == 2: # pivoteo escalonado
row_maxColumn = pivotE(a,colum,s)
if row_maxColumn != colum:
a = pivotP(a, row_maxColumn, colum)
P = exchangeRows(P, row_maxColumn, colum)
#print 'P(%d,%d)' % (row_maxColumn, colum)
#printMatrix(rowsPermutMatrix(n, row_maxColumn, colum))
elif piv == 3: # pivoteo total
row, c = maxSubMatrix(a, colum)
if (row != colum) or (c != colum) :
a = pivotT(a, colum)
P = exchangeCols(P, row, colum)
Q = exchangeCols(Q, colum, c)
#print 'P(%d,%d):' % (colum, row)
#printMatrix(rowsPermutMatrix(n, row, colum))
#print 'Q(%d,%d):' % (colum, c)
#printMatrix(rowsPermutMatrix(n, c, colum))
return a, P, Q
# ------------------------------------------------------------
# Privoteo Parcial
# Permuta la fila r1 con la fila r2 de la matriz M
def pivotP(M, r1, r2):
return exchangeRows(M, r1, r2)
# ------------------------------------------------------------
# pivoteo escalonado
# escoge los maximos de cada fila
# y por medio de divisiones escoge el intercambio de filas
def pivotE(M,r,s):
n = len(M)
a = [0.]*n
for i in range(r,n):
a[i] = 1.*abs(M[i][r])/s[i]
ai = a[0]
index = 0
for i in range(1,n):
if a[i]>ai:
ai = a[i]
index = i
return index
# ------------------------------------------------------------
# retorna las proporciones por fila
def escalPortion(M):
n = len(M)
s = [0.]*n
aux = []
for i in range(n):
aux = []
for j in range(n):
aux.append(abs(M[i][j]))
s[i] = max(aux)
return s
# ------------------------------------------------------------
# Privoteo Total
# Busca el mayor elemento de la submatriz iniciada desde A[i][i] y permuta filas y columnas
def pivotT(M, i):
r, c = maxSubMatrix(M, i)
M = pivotP(M, i, r)
return exchangeCols(M, c, i)
# ------------------------------------------------------------
# Calcula la matriz de permutacion de fila
def rowsPermutMatrix(n, r1, r2):
#Matriz identidad
I = [[float(i == j) for j in range(n)] for i in range(n)]
return exchangeRows(I, r1, r2)
# ------------------------------------------------------------
# Calcula la matriz de permutacion de columna
def columsPermutMatrix(n, c1, c2):
#Matriz identidad
I = [[float(i == j) for j in range(n)] for i in range(n)]
return exchangeCols(I, c1, c2)
# ------------------------------------------------------------
# Multiplicacion de 2 matrices C = A*B
def matrixMulti(A, B):
rowsA, colsA = len(A), len(A[0])
rowsB, colsB = len(B), len(B[0])
if colsA != rowsB:
exit('Dimensiones incorrectas')
C = [[0. for row in range(colsB)] for col in range(rowsA)]
for i in range(rowsA):
for j in range(colsB):
for k in range(colsA):
C[i][j] += A[i][k]*B[k][j]
return C
# ------------------------------------------------------------
# Suma de matrices
def matrixSum(A,B):
n = len(A)
m = len(A[0])
C = [[0. for row in range(n)] for col in range(m)]
for i in range(n):
for j in range(m):
C[i][j] = A[i][j] + B[i][j]
return C
# ------------------------------------------------------------
# Resta de matrices
def matrixSus(A,B):
n = len(A)
m = len(A[0])
C = [[0. for row in range(n)] for col in range(m)]
for i in range(n):
for j in range(m):
C[i][j] = A[i][j] - B[i][j]
return C
# ------------------------------------------------------------
# multiplicacion matrix vector
def multiMatrixVector(A,x):
c=[]
col = len(x) # numero filas de b y numero de columnas de A
row = len(A) # numero de filas de A
if col!=len(A[0]):
exit('No tiene longuitudes igual')
for i in range(row):
suma=0.
for j in range(col):
suma += A[i][j]*x[j]
c.append(suma)
return c
# ------------------------------------------------------------
# multiplicacion vector matrix
def multiVectorMatrix(A,x):
c=[]
col = len(x) # numero filas de b y numero de columnas de A
row = len(A[0]) # numero de columnas de A
if col!=len(A):
exit('No tiene longuitudes igual')
for i in range(row):
suma=0.
for j in range(col):
suma += A[j][i]*x[j]
c.append(suma)
return c
# ------------------------------------------------------------
# conviete todo a float
def matrixToFloat(A):
n=len(A)
m=len(A[0])
for i in range(n):
for j in range(m):
A[i][j] = float(A[i][j])
return A
# ------------------------------------------------------------
# convierte un vector a float
def vectorToFloat(P):
return [float(i) for i in P]
# ------------------------------------------------------------
# resta 2 filas, fila i = fila i - fila j*const
def susRowsMatrix(M,i,j,const):
A = [row[:] for row in M]
n = len(A[0])
for m in range(n):
A[i][m] = A[i][m] - const*A[j][m]
return A
# ------------------------------------------------------------
# Suma 2 filas, fila i = fila i - fila j*const
def addRowsMatrix(M,i,j,const):
A = [row[:] for row in M]
n = len(A[0])
for m in range(n):
A[i][m] = A[i][m] + const*A[j][m]
return A
# ------------------------------------------------------------
# producto de una matriz por un escalar
def prodMatrix(M,const):
A = [row[:] for row in M]
n=len(A)
m=len(A[0])
for i in range(n):
for j in range(m):
A[i][j] *=const
return A
# ------------------------------------------------------------
# rotacion de matriz de givens
def rotmat(a,b):
if b==0:
c=1.
s=0.
elif abs(b)>abs(a):
temp = 1.*a/b
s = 1.0 / sqrt( 1.0 + temp*temp )
c = temp * s
else:
temp = b / a
c = 1.0 / sqrt( 1.0 + temp*temp )
s = temp * c
return c,s
# ------------------------------------------------------------
# reemplaza la columna i en la matrix
def replace(V,r,i):
n=len(r)
V = transMatrix(V)
V[i] = r
V = transMatrix(V)
return V
# ------------------------------------------------------------
# aproxima mas la solucion
def iterRefinery(A,b,X,maxiter=100,tol=1e-7):
n = len(b)
for i in range(n):
Ax = multiMatrixVector(A,X)
r0 = [(b[z] - Ax[z]) for z in range(n)]
y = gauss(A, r0,piv=0)
XX = [ X[z] + y[z] for z in range(n) ]
Xxx = [ X[z] - XX[z] for z in range(n) ]
error = eucliNorm(Xxx)
if error<tol or error == 0:
return XX
X = XX[:]
return XX
# ------------------------------------------------------------
# Resuelve la matriz superior U con el metodo de sustitucion inversa
def solMatrixSup(U, b):
x = []
for i in range(len(U)-1,-1,-1):
if(U[i][i]!=0):
x.append((1.0/(U[i][i]))*(b[i]-sum(U[i][len(U)-j-1]*x[j] for j in range(len(x)))))
else:
x.append(0.0)
x.reverse()
return x
# ------------------------------------------------------------
# Resuelve la matriz inferior L con el metodo de sustitucion inversa
def solMatrixInf(L, b):
x = []
for i in range(len(L)):
if(L[i][i]!=0):
x.append((1.0/(L[i][i]))*(b[i]-sum(L[i][j]*x[j] for j in range(len(x)))))
else:
x.append(0.0)
return x
# ------------------------------------------------------------
# Se usa para resolver la matriz superior generada por gauss y gauss-Jordan
def backSustitution(a):
n = len(a)
x = [0]*n
for j in range(n-1, -1, -1):
x[j] = (a[j][n] - sum(a[j][k]*x[k] for k in range(j+1, n)))/float(a[j][j])
return x
# ------------------------------------------------------------
# Se usa para calcular el maximo elemento de una diagonal
def maxDiagon(A,i):
n = len(A)
maxim = A[i][i]
index = i
for p in range (i,n):
if fabs(A[p][p])>maxim:
maxim = A[p][p]
index = p
maxim = fabs(maxim)
return maxim,index
# ------------------------------------------------------------
# Se usa para calcular el maximo elemento de una diagonal
def isPosSemiDef(A):
n = len(A)
for i in range(n):
if i!=maxRow(A,i):
# print "Debe ser aii el maximo"
return False
for j in range(n):
if i!=j:
if fabs(A[i][j])>(A[i][i]+A[j][j])/2:
# print "debe ser <= que la media aritmetica"
return False
if fabs(A[i][j])>sqrt(A[i][i]*A[j][j]):
# print "debe ser <= que la media geometrica"
return False
if A[i][i]==0:
if A[i][j]!=0 and A[j][i]!=0:
return False
return True
# ------------------------------------------------------------
# dominancia de una matriz
def dominance(A):
n=len(A)
m=len(A[0])
for j in range(n):
dominancia = 0.0
for i in range(j+1, m):
if j != i:
dominancia += fabs(A[i][j])
if A[i][i] < dominancia:
return False
return True
# ------------------------------------------------------------
|
c8e34b3e8a86ed660329deaf20be620a3aced6e9 | srishav9/hellopythonworld | /Dictionaries/alias_copy.py | 512 | 3.921875 | 4 |
#ALIAS
opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}
alias = opposites
print(opposites)
print("alias = opposites")
print("The 'is' operator shows if two objects are same")
print("alias is opposites",alias is opposites)
alias['right'] = 'left'
print("alias['right'] = 'left'")
print("opposites['right']:",opposites['right'])
#COPY
acopy=opposites.copy()
print("acopy=opposites.copy()")
print("acopy['right'] = 'wrong'")
acopy['right'] = 'wrong'
print(opposites,"Original object is not changed")
|
fce0f3e50e3a269822276dcf1bef8c3d3e0b3afd | Yogesh-Singh-Gadwal/YSG_Python | /Advance_Python/Day-30/3.py | 200 | 3.5 | 4 | # Encapsulation
# without
class Myclass():
# class variable
__a = 10
print(__a)
c = Myclass()
print(c.__a) #AttributeError: 'Myclass' object has no attribute '__a'
|
41c40a3ac936dabc6b0c2248cca9374847b44064 | AlienWu2019/Alien-s-Code | /test/test9.py | 1,841 | 3.984375 | 4 | def power(x):
return x*x
print(power(2))
def power(x,n):
s=1
while n>0:
n=n-1
s=s*x
return s
print(power(5,2))
def enroll(name,gender,age=6,city='Beijing'):
print('name:',name)
print('gender:',gender)
print('age',age)
print('city',city)
enroll('Sarah','F')
def add_end(L=[]):
L.append('END')
return L
print(add_end([1,2,3]))
print(add_end(['x','y','z']))
print(add_end())
print(add_end())
def add_end(L=None):
if L is None:
L=[]
L.append('END')
return L
def calc(numbers):
sum=0
for n in numbers:
sum=sum+n*n
return sum
print(calc([1,2,3]))
def calc(*numbers):
sum=0
for n in numbers:
sum=sum+n*n
return sum
print(calc(1,2))
nums=[1,2,3]
print(calc(*nums))
def person(name,age,**kw):
print('name:',name,'age:',age,'other:',kw)
print(person('Michael',30))
person('Bob',35,city='Beijing')
person('Adam',45,gender='M',job='Engineer')
extra={'city':'Beijing','job':'Engineer'}
print(person('jack',24,**extra))
def person(name,age,**kw):
if 'city' in kw:
pass
if 'job' in kw:
pass
print('name:',name,'age:',age,'other:',kw)
print(person('jack',24,city="Beijing",addr='Chaoyang',zipcode=123456))
def person(name,age,*,city,job):
print(name,age,city,job)
print(person('jack',24,city='beijing',job='Engineer'))
def f1(a,b,c=0,*args,**kw):
print('a=',a,'b=',b,'c=',c,'args=',args,'kw=',kw)
def f2(a,b,c=0,*,d,**kw):
print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
print(f1(1,2))
print(f1(1,2,c=3))
print(f1(1,2,3,'a','b'))
print(f1(1,2,3,'a','b',x=99))
print(f2(1,2,d=99,ext=None))
args=(1,2,3,4)
kw={'d':99,'x':'#'}
print(f1(*args,**kw))
args=(1,2,3)
kw={'d':88,'x':'#'}
print(f2(*args,**kw))
def product(x,*y):
for i in y:
x=x*i
return x
print(product(1,2,5,8))
|
ac0ca45de03da9e85d16cbd00e07595e92ceb8cc | Ethan2957/p02.1 | /fizzbuzz.py | 867 | 4.5 | 4 | """
Problem:
FizzBuzz is a counting game. Players take turns counting the next number
in the sequence 1, 2, 3, 4 ... However, if the number is:
* A multiple of 3 -> Say 'Fizz' instead
* A multiple of 5 -> Say 'Buzz' instead
* A multiple of 3 and 5 -> Say 'FizzBuzz' instead
The function fizzbuzz should take a number and print out what the player
should say.
Tests:
>>> fizzbuzz(7)
7
>>> fizzbuzz(10)
Buzz
>>> fizzbuzz(12)
Fizz
>>> fizzbuzz(30)
FizzBuzz
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
doctest.testmod(verbose=True)
# Edit this function
def fizzbuzz(n):
if n %3 == 0 and n %5 == 0:
print("FizzBuzz")
elif n %3 == 0:
print("Fizz")
elif n %5 == 0:
print("Buzz")
else:
print(n)
|
c3bb9f558afc8de740d42a84e999ad8e8ef30316 | minjjjae/pythoncode | /flasktest/flaskjinja/files/test3.py | 2,951 | 3.890625 | 4 | import sys
# student={'idx':0,'name':'','major':'','adr':'','number':0}
class student:
def __init__(self):
self.studentlist=[
{'idx':1,'name':'a','major':'d','adr':'o','number':1},
{'idx':2,'name':'b','major':'e','adr':'p','number':1},
{'idx':3,'name':'c','major':'f','adr':'q','number':1},
]
def Enrollment(self):
student={}
while True:
idx=input("학번을 입력하세요 >> ")
if idx.isdecimal():
idx=int(idx)
break
else:
print("숫자를 입력해주세요")
name=input("학생이름을 입력하세요 >> ")
major=input("전공를 입력하세요 >> ")
adr=input("주소를 입력하세요 >> ")
while True:
number=input("전화번호를 입력해주세여 >> ")
if number.isdecimal():
number=int(number)
break
else:
print("숫자를 입력해주세요")
student['idx']=idx
student['name']=name
student['major']=major
student['adr']=adr
student['number']=number
self.studentlist.append(student)
print(self.studentlist)
def Update(self):
student={}
print("학생정보를 수정합니다.")
idx=int(input("수정할 학번을 입력하세요 >> "))
for i in range(0,len(self.studentlist)):
if self.studentlist[i]['idx']==idx:
name=input("학생이름을 입력하세요 >> ")
major=input("전공을 입력하세요 >> ")
adr=input("주소를 입력하세요 >> ")
number=int(input("전화번호를 입력해주세여 >> "))
student['idx'] = idx
student['name']=name
student['major']=major
student['adr']=adr
student['number']=number
self.studentlist[i]=student
break
print(self.studentlist)
def Delete(self):
idx=int(input("삭제할 학번을 입력하세요 >> "))
for i in range(0,len(self.studentlist)):
if self.studentlist[i]['idx']==idx:
del self.studentlist[i]
break
def List(self):
for i in range(0,len(self.studentlist)):
print(self.studentlist[i])
def Quit(self):
print("종료합니다.")
sys.exit()
def exe(self, menu):
if menu=='1':
self.Enrollment()
elif menu=='2':
self.Update()
elif menu=='3':
self.Delete()
elif menu=='4':
self.List()
elif menu=='5':
self.Quit()
student = student()
while True:
menu=input('''
1. 학생등록
2. 수정
3. 삭제
4. 목록
5. 종료
''')
student.exe(menu)
|
d6a7daa38932e1f06377d5ff30e42dee72a78a84 | goblindegook/katas | /python/katas/fizzbuzz.py | 338 | 3.96875 | 4 | from typing import List
def fizzbuzz(start: int, end: int) -> List[str]:
return [convert(x) for x in range(start, end + 1)]
def convert(n: int) -> str:
if n % 3 == 0 and n % 5 == 0:
return "fizzbuzz"
elif n % 5 == 0:
return "buzz"
elif n % 3 == 0:
return "fizz"
else:
return f"{n}"
|
e0114604e1148e897e29e3fbfc6c449da6fa0f3e | rugbyprof/2143-ObjectOrientedProgramming | /ClassLectures/day10.py | 1,361 | 4.0625 | 4 | class Node(object):
def __init__(self,val):
self.data = val
self.left_child = None
self.right_child = None
self.parent = None
def setVal(self,val):
self.data = val
def setLeftChild(self,node):
self.left_child = node
self.left_child.parent = self
def setRightChild(self,node):
self.right_child = node
self.right_child.parent = self
def __str__(self):
return "%d" % (self.data)
class BST(object):
def __init__(self):
self.root = None
def __traverse(self,root):
if root == None:
return
elif
def print(self)
self.__traverse(self.root)
def insert(self,data):
# if no root exists
if self.root == None:
self.root = Node(data)
# otherwise find location to insert
else:
parent = self.root
temp = self.root
direction = ""
while not temp == None:
parent = temp
if temp.data > data:
direction = "left"
temp = temp.left_child
else:
direction = "right"
temp = temp.right_child
if direction == "left":
parent.left_child = Node(data)
parent.left_child.parent = parent
else:
parent.right_child = Node(data)
parent.right_child.parent = parent
tree = BST()
tree.insert(34)
|
831f980025644768823f109f00bc1ae2c224db53 | xiang-daode/Python3_codes | /X020_tkinter_4图片按钮动画设计器.py | 2,046 | 3.8125 | 4 | # 在这里写上你的代码 :-)
import math
import time
import tkinter as tk
root = tk.Tk()
root.title("动画设计器 ----设计:项道德")
w = tk.Canvas(root, width=1200, height=600)
w.pack()
x0, y0 = 600, 300
lb = tk.Label(
text="---------by daode1212 2021-04-06-----------", fg="#993300", bg="#00EEFF"
).pack(side="bottom")
def myDrawA(u):
r = 150
while u < 1000:
x1, y1 = x0, y0
x2, y2 = x0 + r * math.cos(u / 60), y0 + r * math.sin(u / 60)
w.create_line(x1, y1, x2, y2, fill="#00FF44", width=8)
w.update()
time.sleep(0.001)
w.delete("all")
u += 3
def myDrawB(u):
r = 200
while u < 1000:
x1, y1 = x0, y0
x2, y2 = x0 + r * math.cos(u / 160), y0 + r * math.sin(u / 160)
w.create_line(x1, y1, x2, y2, fill="#0044FF", width=8)
w.update()
time.sleep(0.001)
w.delete("all")
u += 5
def myDrawC(u):
r = 250
while u < 1000:
x1, y1 = x0, y0
x2, y2 = x0 + r * math.cos(u / 90), y0 + r * math.sin(u / 60)
w.create_line(x1, y1, x2, y2, fill="#FF0044", width=8)
w.update()
time.sleep(0.001)
w.delete("all")
u += 10
def myDrawD(u):
r = 250
while u < 1000:
x1, y1 = x0, y0
x2, y2 = x0 + r * math.cos(u / 90), y0 + r * math.sin(u / 60)
w.create_line(x1, y1, x2, y2, fill="#FF4400", width=8)
w.update()
time.sleep(0.001)
w.delete("all")
u += 15
photo = tk.PhotoImage(file="按钮.png")
tk.Button(
root, text="[按钮A]", command=(lambda: myDrawA(0)), image=photo, compound="center"
).pack(side="left")
tk.Button(
root, text="[按钮B]", command=(lambda: myDrawB(0)), image=photo, compound="center"
).pack(side="left")
tk.Button(
root, text="[按钮C]", command=(lambda: myDrawC(0)), image=photo, compound="center"
).pack(side="left")
tk.Button(
root, text="[按钮D]", command=(lambda: myDrawD(0)), image=photo, compound="center"
).pack(side="left")
root.mainloop()
|
9a8361187ad419b7ea503818571413eb332617bc | ViniciusRomano/oficina-python | /ex6.py | 331 | 4.125 | 4 | cond = True
while(cond):
frase = input("Me de uma frase com mais de dois a's, meu chapa\n")
if(frase.count('a') >= 2):
cond = False
## Método um pouquinho mais bonito
# cond = True
# while(cond):
# frase = input("Me de uma frase com mais de dois a's, meu chapa\n")
# cond = frase.count('a') < 3
|
384331b6c335d28a1795488ffd95bd2534f9735d | mkebrahimpour/DataStructures_Python | /GeeksForGeeks/Binary Trees/inorder_without_recursion.py | 784 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 20:03:11 2019
@author: sbk
"""
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.data = key
def inOrder(tree):
stack = []
done = 0
current = tree
while(not done):
if current is not None:
stack.append(current)
current = current.left
else:
if len(stack) > 0:
current = stack.pop()
print(current.data)
current = current.right
else:
done = 1
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
inOrder(root)
|
1835c66c908232518fdcdce0f7cb6293528fb7c6 | jmcs811/interview_prep | /ctci/2_linked_lists/2_return_kth_to_last.py | 998 | 3.734375 | 4 | # problem: implement and algorithm to find the kth to the last element
# Example
# INPUT 1 -> 2 -> 3 -> 4 -> NONE, 2
# OUTPUT 1 -> 2 -> 4 -> NONE
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
class Solution:
def findKthFromEnd(self, head: ListNode, n: int) -> ListNode:
# get the count
count = 1
on = head
while on != None:
count += 1
on = on.next
one_before_removed = count - n
if one_before_removed <= 0:
return head.value
if one_before_removed == 0:
return head.next
on = head
while one_before_removed > 1:
one_before_removed -= 1
on = on.next
return on.value
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
test = Solution()
print(test.findKthFromEnd(head, 4)) |
bc6732284a4bc80f586d2df941046fa76b0b830e | Sangewang/PythonBasicLearn | /OJ/CountWord.py | 621 | 4.03125 | 4 | def CountWords(strLine):
count = len(strLine)
print 'The Length of strLine is ',count
result = {'alpha':0,'space':0,'digit':0,'others':0}
for i in xrange(count):
if 'a'<=strLine[i]<='z' or 'A'<=strLine[i]<='Z':
result['alpha'] += 1
elif ' ' == strLine[i]:
result['space'] += 1
elif '\n' == strLine[i]:
break
elif '1'<=strLine[i]<='9':
result['digit'] += 1
else:
result['others'] += 1
return result
print CountWords('255.255.255.0\n is a ipv4 address')
print CountWords('255.255.255.a is not a ipv4 address.\n')
print CountWords('')
print CountWords("\0\n")
|
89971fbb031ae17d2f3ad5482c33c5f0d1c517d7 | ankitsingh03/code-python | /gfgs/Array/3. array rotation.py | 136 | 3.921875 | 4 | def rotate(lst, l):
for i in range(l):
lst.append(lst.pop(0))
return lst
lst = [1, 2, 3, 4, 5]
print(rotate(lst, 2))
|
96ba8d368679598144e7e81c31186a0b94030475 | Nushrat-Nishi/PythonUnload | /pythonPure/w3schools/_3_Set.py | 496 | 4.15625 | 4 | # A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
aSet = {"apple", "banana", "cherry"}
print(aSet)
bSet = set(("apple", "banana", "cherry"))
print("Using the set() constructor to make a set:", bSet)
bSet.add("Strawberry")
print("Using the add() method to add an item:", bSet)
bSet.remove("banana")
print("Using the remove() method to remove an item : ", bSet)
print("Using the len() method to return the number of items : ", len(bSet)) |
0994d2cd9ef463e01e93a4ecf8a5cf678cc885cf | varunrau/SmartDataStructure | /minheap.py | 1,153 | 3.859375 | 4 | # The Heap with Heap property = min
import heapq
class MinHeap:
"""
Creates an array.
"""
def __init__(self):
self.array = []
"""
True iff the item is in the array.
"""
def contains(self, key):
for x in self.array:
if x == key:
return True
return False
"""
Adds the item to the array.
"""
def add(self, key):
heapq.heappush(self.array, key)
"""
Removes the item from the array.
"""
def remove(self, key):
#stack = []
#while (True):
# val = heapq.heappop(self.array)
# stack.append(val)
# if val == key:
# break
#toReturn = stack.pop()
#for x in stack:
# self.add(x)
#return toReturn
return 0
"""
Returns the item at index index
"""
def get(self, index):
#stack = []
#for x in range(index-1):
# stack.append(heapq.heappop(self.array))
#toReturn = heapq.heappop(self.array)
#for x in stack:
# self.add(x)
#return toReturn
return 0
|
331be9b16a4522a7a47b6bef2415dd8c7db63f1e | andrei406/Meus-PycharmProjects-de-Iniciante | /PythonExercicios/ex062.py | 426 | 3.71875 | 4 | n1 = int(input('Digite o primeiro termo da PA: '))
n2 = int(input('Digite agora a razão da PA: '))
c = 0
s = n1
q = 10
ch = True
t = 10
while ch == True:
while c != q:
print(s, end=' --> ')
s += n2
c += 1
q = int(input('\nQuantos mais termos quer ver? Caso não queira mais ver\nDigite 0: '))
c = 0
t += q
if q == 0:
ch = False
print('Forão mostrados {} termos'.format(t)) |
d341cff1a9c1e4dd410bb39bb1f1a812156e98f6 | romanpindela/pa-music-library-pa-python-master-progbasic-python-codecool | /music_reports.py | 3,339 | 3.859375 | 4 | from file_handling import *
artist_col = 0
album_col = 1
year_col = 2
genre_col = 3
length_col = 4
def get_albums_by_genre(albums, genre):
"""
Get albums by genre
:param list albums: albums' data
:param str genre: genre to filter by
:returns: all albums of given genre
:rtype: list
"""
genres = set(album[genre_col] for album in albums)
if genre in genres:
genre_albums = []
for album in albums:
if album[genre_col] == genre:
genre_albums.append(album)
return genre_albums
else:
raise ValueError("Wrong genre")
def get_genre_stats(albums):
"""
Get albums' statistics showing how many albums are in each genre
Example: { 'pop': 2, 'hard rock': 3, 'folk': 20, 'rock': 42 }
:param list albums: albums' data
:returns: genre stats
:rtype: dict
"""
genre_stats = {}
for album in albums:
if album[genre_col] in genre_stats:
genre_stats[album[genre_col]] = genre_stats[album[genre_col]] + 1
else:
genre_stats[album[genre_col]] = 1
return genre_stats
def get_longest_album(albums):
"""
Get album with biggest value in length field.
If there are more than one such album return the first (by original lists' order)
:param list albums: albums' data
:returns: longest album
:rtype: list
"""
longest_album = albums[0]
for album in albums:
if to_time(album[length_col]) > to_time(longest_album[length_col]):
longest_album = album
return longest_album
def get_last_oldest(albums):
"""
Get last album with earliest release year.
If there is more than one album with earliest release year return the last
one of them (by original list's order)
:param list albums: albums' data
:returns: last oldest album
:rtype: list
"""
oldest_album = albums[0]
for album in albums:
if int(album[year_col]) <= int(oldest_album[year_col]):
oldest_album = album
return oldest_album
def get_last_oldest_of_genre(albums, genre) -> list:
"""
Get last album with earliest release year in given genre
:param list albums: albums' data
:param str genre: genre to filter albums by
:returns: last oldest album in genre
:rtype: list
"""
genre_albums = []
for album in albums:
if album[genre_col] == genre:
genre_albums.append(album)
return get_last_oldest(genre_albums)
def to_time(album_length: str):
"""
converts time in format "minutes:seconds" (string) to seconds (int)
"""
minutes_col = 0
seconds_col = 1
minutes_seconds = album_length.split(":")
total_seconds = (int(minutes_seconds[minutes_col])*60) + (int(minutes_seconds[seconds_col]))
return total_seconds
def get_total_albums_length(albums):
"""
Get sum of lengths of all albums in minutes, rounded to 2 decimal places
Example: 3:51 + 5:20 = 9.18
231 + 320 seconds = 551 seconds
:param list albums: albums' data
:returns: total albums' length in minutes
:rtype: float
"""
sum_of_seconds = 0
for album in albums:
sum_of_seconds += to_time(album[length_col])
minutes = round((sum_of_seconds / 60),2)
return minutes |
5d67145e6eeba9d64a50a125a6bf32a9d2d22099 | chaitrak05/CA2020_Assignment_Chaitra | /Functions/uppercaselist_5.py | 210 | 4 | 4 | list = []
def uppercase(l,list):
list.append(l.upper())
return list
while True:
l = input()
if l:
list = uppercase(l,list)
else:
break
for l in list:
print(l)
|
c79290ded36eb5bd4401bf8c07189246c843cc23 | GLV83/lab-python | /lab_7.py | 4,829 | 3.953125 | 4 | from math import asin, sinh, fabs
import numpy as np
print('Вариант 7')
print('ЗАДАНИЕ. Найдите значения выражений:')
print('Y = -asin(4 * a^2 - 3 * a * x - 7 * x^2)')
print('G = 5(27 * a^2 - 51 * a * x + 20 * x^2)/-10 * a^2 + 21 * a * x + 27 * x^2)')
print('F = sinh(2 * a^2 + 21 * a * x + 10 * x^2)')
print('РЕШЕНИЕ:')
#Список для результатов
result1 = []
result2 = []
result3 = []
result = {'Y':result1, 'G':result2, 'F':result3}
while True:
try:
# Ввод значений
min_x_and_a = float(input('Введите значение min:'))
max_x_and_a = float(input('Введите значение max:'))
if min_x_and_a >= max_x_and_a:
print('ОШИБКА. Минимум равен или больше максимума! Введите новые значения')
continue
else:
step_x_a = float(input('Введите шаг значений x и a:'))
if step_x_a <= 0:
print('Шаг значений x и а не может быть меньше или равен 0. Повторите ввод значений.')
continue
step = int(input('Введите количество шагов вычисления функции:'))
if fabs((min_x_and_a - max_x_and_a) / step_x_a) <= step:
print('Количество шагов вычисления функции превысило максимальное значение. Повторите ввод значений, уменьшив количество шагов.')
continue
except ValueError:
print('Переключите язык. Повторите ввод значений.')
continue
# Автоматический подбор значений x и a
for x in np.arange(min_x_and_a, max_x_and_a, step_x_a):
for a in np.arange(min_x_and_a, max_x_and_a, step_x_a):
try:
Y = -asin(4 * a**2 - 3 * a * x - 7 * x**2)
if -1 <= Y <= 1:
result1.append(float(round(Y,5)))
except ValueError:
print ('Значения не удовлетворяют условию Y. Введите новые значения')
break
try:
#G = (5 * (27 * a**2 - 51 * a * x + 20 * x**2))/(-10 * a**2 + 21 * a * x + 27 * x**2)
nam = 5 * (27 * a**2 - 51 * a * x + 20 * x**2)
nam_1 = -10 * a**2 + 21 * a * x + 27 * x**2
G = nam / nam_1
if nam_1 != 0:
result2.append(float(round(G,5)))
except ZeroDivisionError:
print ('Не удается найти G. На ноль делить нельзя! Введите новые значения')
break
try:
F = sinh(2 * a**2 + 21 * a * x + 10 * x**2)
if F == sinh(2 * a**2 + 21 * a * x + 10 * x**2):
result3.append(float(round(F,5)))
except OverflowError:
print ('Ошибка математического диапазона F. Введите новые значения')
break
#else:
#print('x = {}, a = {}, шаг = {}'.format(round(x,5), round(a,5), round(step_x_a,5)))
#print('Y = {}'.format(Y))
#print('G = {}'.format(G))
#print('F = {}'.format(F))
#print('ОТВЕТ: Y = {}, G = {}, F = {}'.format(round(Y,3),round(G,3),round(F,3)))
#print('')
#break
# Цикл расчета
count = 0
while count < step:
#np.arange(min_x_and_a, max_x_and_a, step_x_a)
min_x_and_a += step_x_a
if min_x_and_a > max_x_and_a:
break
count += 1
break
# Запись в файл
with open('GLV_lab.txt', 'w') as file:
for key, step_x_a in result.items():
file.write('{} = {}\n' .format(key, step_x_a))
# Очистка словаря
result = {}
# Чтение из файла
with open('GLV_lab.txt', 'r') as file:
for i in file.readlines():
key, step_x_a = i.strip().split('=')
print(key, '=', step_x_a)
# Вывод максимального и минимального значения
#print('Минимальные значения: Y = {}, G = {}, F = {}'.format(min(result1),min(result2),min(result3)))
#print('Максимальное значение: Y = {}, G = {}, F = {}'.format(max(result1),max(result2),max(result3)))
|
0b64b40208e22803a2b44676dfb41284ba69d1ef | SnowSuo/test | /numbergame.py | 1,133 | 3.859375 | 4 | #-*-coding UTF-8 -*-
'''
guess number game.py
============================
猜数字游戏,有三次机会可供猜取
@author: SnowSuo
@date: 2018-04-16
'''
#导入随机数函数模块
import random #调用随机函数
#游戏入口布局
print('----------一起玩个猜数字游戏-------------')
#数字进行整型
temp=int(input('请输入一个数字:>-') )
times=2
#定义数字区间为1-10
a=random.randint(1,10)
if a<temp:
print('数字有点大')
else:
print('数字有点小')
#当输入的数字不等于要猜的数字,并且猜数的次数大于0
while temp!=a and times>0:
temp=int(input('猜错了,重新输入一个数字吧:>- '))
times=times-1
if temp==a:
print('这么NB,这样都被你猜中了。')
else:
if temp>a:
print('数字大了你还有'+str(times)+'次机会')
else:
print('数字小了,请重新输入')
if times<=0:
print('次数用完')
print('游戏结束')
|
41e78414e48f720c1f2d0247d97953a21c3bb542 | ksayee/programming_assignments | /python/CodingExercises/LeetCode1009.py | 1,675 | 3.65625 | 4 | '''
1009. Complement of Base 10 Integer
Easy
Every non-negative integer N has a binary representation.
For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation.
The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary.
For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.
Example 1:
Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:
Input: 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
'''
def GetBinary(num):
lst=[]
while num!=0:
rem=num%2
num=num//2
lst.append(str(rem))
lst.reverse()
return ''.join(lst)
def GetComplement(bin_num):
lst=[]
for i in range(0,len(bin_num)):
if bin_num[i]=='0':
lst.append(1)
else:
lst.append(0)
return lst
def LeetCode1009(num):
bin_num=GetBinary(num)
com_num=GetComplement(bin_num)
sum=0
k=0
for i in range(len(com_num)-1,-1,-1):
sum=sum+(com_num[i]*(2**k))
k=k+1
return sum
def main():
num=5
print(LeetCode1009(num))
num = 7
print(LeetCode1009(num))
num = 10
print(LeetCode1009(num))
if __name__=='__main__':
main() |
29521366fa90f444174418a871cb7b6b01493d30 | Flavio-Varejao/Exercicios | /Python/Listas/Q6.py | 726 | 3.703125 | 4 | '''
Faça um Programa que peça as quatro notas de 3 alunos,
calcule e armazene num vetor a média de cada aluno,
imprima o número de alunos com média maior ou igual a 7.0.
'''
notas={}
medias=[]
contador=0
for nota in range(1,4):
nome=input("\nDigite o seu nome: ")
notas[nome]=[
float(input("Digite a 1ª nota: ")),
float(input("Digite a 2ª nota: ")),
float(input("Digite a 3ª nota: ")),
float(input("Digite a 4ª nota: "))]
for nome,nota in notas.items():
medias.append(sum(nota)/4)
for media in medias:
if media >= 7:
contador+=1
print("\nNotas dos alunos:\n",notas)
print("Médias dos alunos:\n",medias)
print("Alunos com média maior ou igual a 7:",contador) |
479a4495290a4bf9ef217975d44272cb7304f844 | Vikktour/Data-Structures-Algorithms-Implementations | /Two Pointers/LC88. Merge Sorted Array (Easy).py | 3,090 | 4.03125 | 4 | """
Victor Zheng
01-11-2021
88. Merge Sorted Array (Easy)
"""
"""
Approach: O(n) runtime, O(1) extra space
1) move values of nums1 to end of array
Ex:
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
nums1 --> [0,0,0,1,2,3]
2) iterate between nums1[shiftidx] and nums2[i] and take the min and place in nums1 in order from left to right. Replace used values with 0.
nums1 = [1,0,0,0,2,3] nums2 = [2,5,6]
nums1 = [1,2,0,0,0,3] nums2 = [2,5,6]
nums1 = [1,2,2,0,0,3] nums2 = [0,5,6]
nums1 = [1,2,2,3,0,0] nums2 = [0,5,6]
nums1 = [1,2,2,3,5,0] nums2 = [0,0,6]
nums1 = [1,2,2,3,5,6] nums2 = [0,0,0]
Note that setting to 0 is not necessary, but is easier for visualization.
Discussion post: https://leetcode.com/problems/merge-sorted-array/discuss/1011844/python-3-pointer-indexing-with-explanation-on-runtime-o1-extra-space
"""
from typing import List
class Solution:
#36ms ~ O(n) runtime, O(1) extra space
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
#move nums1 values to the end of nums1
for index in range(m-1,-1,-1):
nums1[index+n] = nums1[index]
if n != 0:
nums1[index] = 0
#iterate nums1 & nums2, and put the min in front of nums1
idx1 = n
idx2 = 0
idx1Left = 0
while idx1 < len(nums1) and idx2 < len(nums2):
if nums1[idx1] <= nums2[idx2]:
min = nums1[idx1]
nums1[idx1] = 0
idx1 += 1
else:
min = nums2[idx2]
nums2[idx2] = 0
idx2 += 1
nums1[idx1Left] = min
idx1Left += 1
#one of the arrays are done iterating, fill with the other orray
if idx1 == len(nums1):
#fill array with rest of nums2
while idx2 < len(nums2):
nums1[idx1Left] = nums2[idx2]
idx2 += 1
idx1Left += 1
elif idx2 == len(nums2):
#fill array with rest of nums1
while idx1 < len(nums1):
nums1[idx1Left] = nums1[idx1]
idx1 += 1
idx1Left += 1
#print("nums1: {}".format(nums1))
return
def main():
nums1,m,nums2,n = [1,2,3,0,0,0], 3, [2,5,6], 3
#nums1,m,nums2,n = [1], 1, [], 0 #[1]
#nums1,m,nums2,n = [0], 0, [2], 1 #[2]
nums1,m,nums2,n = [1,2,4,5,6,0],5,[3],1 #[1,2,3,4,5,6]
inputs = []
testingOneInput = True
if testingOneInput:
#Test single input
print("Input: {},{},{},{}".format(nums1,m,nums2,n))
solution = Solution()
output = solution.merge(nums1,m,nums2,n)
print("Output: {}".format(output))
"""
else:
#Test multiple inputs
solution = Solution()
for input in inputs:
output = solution.func(input)
print("Input: {0}, Output: {1}".format(input, output))
"""
if __name__ == main():
main() |
4ed957a37a18ffdca0712a5ac70c121187f3f4ab | dgabsi/GoodReads_genre_recognition | /goodreads/baseline.py | 1,376 | 3.5625 | 4 | import numpy as np
import pandas as pd
class Baseline(object):
"""
Baseline model. Based on predicting the former genre of an author(otherwise return genre mode)
"""
def __init__(self, preprocessed_cols):
self.preprocessed_cols = preprocessed_cols
def fit(self, X, y):
"""
Fitting the model in this case we only means saving the training data and finding the mode
"""
self.data = pd.DataFrame(np.hstack((X, y)), columns=self.preprocessed_cols)
self.target_mode = self.data["genre"].mode().values[0]
def predict(self, X):
"""
For prediction we we only search for the book author in the train data and if found return the genre of the other book by the same author .
If not found return genre mode.
"""
author_id_ind = self.preprocessed_cols.index("author_id")
y_predict = pd.Series(X[:, author_id_ind]).apply(self.find_genre_by_author).values
return y_predict
def find_genre_by_author(self, author_id):
"""
Service function to find the genre of the first book of a author in the train data. to be used by predict()
"""
if author_id in self.data["author_id"].values:
return self.data.loc[self.data["author_id"] == author_id, "genre"].values[0]
else:
return self.target_mode
|
21e2db52e850fb042b686c3d04bb58bab6f68bc0 | nilankh/QuestionsOfCoding | /ratinamaze.py | 1,039 | 3.9375 | 4 | def printPathHelper(x, y, maze, n, solution):
#Destination Cell
if x == n - 1 and y == n - 1:
solution[x][y] = 1
print(solution)
return
# these are the Blocking Points
if x < 0 or y < 0 or x >=n or y >= n or maze[x][y] == 0 or solution[x][y] == 1:
return
solution[x][y] = 1
#print("solution first wala",solution)
#down
printPathHelper(x + 1, y, maze, n, solution)
#right
printPathHelper(x, y + 1, maze, n, solution)
#top
printPathHelper(x - 1, y, maze, n, solution)
#left
printPathHelper(x, y - 1, maze, n, solution)
solution[x][y] = 0
## print("solutionnn", solution)
## print("solution", x, '==',y)
return
def printPath(maze):
n = len(maze)
solution = [[0 for j in range(n)]for i in range(n)]
#print(solution)
printPathHelper(0, 0, maze, n, solution)
n = int(input())
maze = []
for i in range(n):
row = [int(ele) for ele in input().split()]
maze.append(row)
printPath(maze)
|
d6975fa21b753f1926bf59cbd24d722df27e4eda | Lucimore/Coffee_machine | /Problems/The Louvre/task.py | 487 | 3.953125 | 4 | class Painting:
museum = "Louvre"
def __init__(self, title, artist, year):
self.title = title
self.artist = artist
self.year = year
masterpiece = Painting(input(), input(), input())
print('"{}" by {} ({}) hangs in the {}.'.format(masterpiece.title,
masterpiece.artist,
masterpiece.year,
masterpiece.museum))
|
2efd95b5c0c74dbbf2dc06d5a9f04ed49f470578 | JanainaNascimento/ExerciciosPython | /ex 058.py | 1,268 | 4.21875 | 4 | '''
Melhore o jogo do Desafio 028 onde o computador vai "Pensar" em um número entre 0 e 10.
Só que agora o jogador vai tentar adivinhar ate acertar
mostrando no final quantos palpites foram necessários para vencer.
'''
# from random import randint
#
# tentativas = 0
# pc = randint(0, 10)
#
# print('O computador pensou um número entre 0 e 10 tente adivinhar')
#
# while True:
# adivinha = int(input('Digite um número para tentar adivinhar: \n'))
# tentativas += 1
# if pc == adivinha:
# print(f'Usuário adivinhou o número é \033[33m{pc}\033[m, parabéns!')
# break
# elif pc != adivinha:
# print('\033[31mEstá errado, tente outro palpite!\033[m')
# print(f'O usuário fez \033[33m{tentativas}\033[m tentativas até acertar o número que o PC pensou.')
from random import randint
computador = randint(0, 10)
print('Tente adivinha o numero entre 0 e 10 que o pc pensou.')
acertou = False
palpites = 0
while not acertou:
jogador = int(input('Qual é seu palpite: '))
palpites += 1
if jogador == computador:
acertou = True
else:
if jogador < computador:
print('mais...')
else:
print('menos...')
print(f'acertou com {palpites} tentativas. Parabéns!')
|
d90f1eafceba3dee485072697d189728fbe07295 | qwerty-123456-ui/pythontuts | /sum33.py | 1,241 | 3.640625 | 4 | # # list comprehension
# s=[i**2 for i in range(1,11)]
# print(s)
#
# n=[-i for i in range(1,11)]
# print(n)
#
# na=['Isha','Kat','Aaron']
# nf=[i[0] for i in na]
# print(nf)
#
# # ex1
# def revs(l):
# l1=[i[::-1] for i in l]
# return l1
# print(revs(['abc','xyz','pqr']))
#
# # with if statement
# l=[i for i in range(1,11) if i%2==0]
# print(l)
# l=input("Enter a list :(, separated)").split()
# print(l)
# for i in l:
# print(type(i))
# if (type(i)==str or type(list(i)==list)):
# l.remove(i)
# l1=[i for i in l if type(int(i))==int]
# print(l1)
# # if-else
# n=list(range(1,11))
# n2=[i*2 if i%2==0 else -i for i in n]
# print(n2)
# # nested list comprehension
# e=[[1,2,3],[1,2,3],[1,2,3]]
# ne=[[ i for i in range(1,4)] for j in range(3)]
# print(ne)
#
#
# # dict comprehension
# sq={f"square of {num} is":num**2 for num in range(1,11)}
# print(sq)
# for k,v in sq.items():
# print(f"{k}:{v}")
# s="Harshit"
# w={char:s.count(char) for char in s}
# print(w)
# # if-else
# d={1:'odd',2:'even'}
# o_e={i:('even' if i%2==0 else 'odd') for i in range(1,11)}
# print(o_e)
#
# # set comprehension
# s={k**2 for k in range(1,11)}
# print(s)
#
# n=['har','IDEA ']
# f={na[0] for na in n}
# print(f)
|
036d1031fc00e1920a6db2888c3a5fbb3b257beb | VZRXS/LeetCode-noob-solutions | /Easy/27_Remove_Element.py | 477 | 3.890625 | 4 | #!/usr/bin/env python3
from typing import List
class Solution(object):
# 27. Remove Element
def removeElement(self, nums: List[int], val: int) -> int:
# Two pointers
slow = 0
for num in nums:
if num != val:
nums[slow] = num
slow += 1
return slow
if __name__ == '__main__':
nums = [3, 2, 2, 3]
val = 3
slow = Solution().removeElement(nums=nums, val=val)
print(nums[:slow:]) |
72fdac67d55b15596e8bf4767476e3055a295ed1 | cifpfbmoll/practica-7-python-egrao | /E5.py | 608 | 3.9375 | 4 | import os
os.system('cls')
#P7E5
#Escribe un programa que te pida una frase y una vocal (entrada por teclado),
# y pase estos datos como parámetro a una función que se encargará de cambiar
# todas las vocales de la frase por la vocal seleccionada. Devolverá la función
# la frase modificada, y el programa principal la imprimirá:
frase=input("Dime algo: ")
vocal=input("Dime una vocal: ")
#dictvocal={"a": vocal, "e": vocal, "i": vocal, "o": vocal, "u": vocal}
def f(a,b):
frase=a.replace("a",b).replace("e",b).replace("i",b).replace("o",b).replace("u",b)
return frase
print(f(frase,vocal))
|
82d746d865712b4466be1b1039a4b654a30ab2df | jerry-mkpong/DataCamp | /Deep_Learning_with_Keras_in_Python/4.Advanced_Model_Architectures/De-noising like an autoencoder.py | 925 | 3.875 | 4 | '''
Okay, you have just built an autoencoder model. Let's see how it handles a more challenging task.
First, you will build a model that encodes images, and you will check how different digits are represented with show_encodings(). You can change the number parameter of this function to check other digits in the console.
Then, you will apply your autoencoder to noisy images from MNIST, it should be able to clean the noisy artifacts.
X_test_noise is loaded in your workspace. The digits in this data look like this:
Apply the power of the autoencoder!
'''
# Build your encoder
encoder = Sequential()
encoder.add(autoencoder.layers[0])
# Encode the images and show the encodings
preds = encoder.predict(X_test_noise)
show_encodings(preds)
# Predict on the noisy images with your autoencoder
decoded_imgs = autoencoder.predict(X_test_noise)
# Plot noisy vs decoded images
compare_plot(X_test_noise, decoded_imgs) |
ad9541275f49c11383fe1b27e89700d6200c2c67 | jwiech/STP-Exercises | /Exercises/chapter13.py | 1,332 | 3.953125 | 4 | class Rectangle():
def __init__(self, l, w):
self.length = l
self.width = w
def perimeter(self):
return self.length * 2 + self.width * 2
class Square():
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
def change_size(self,change):
self.side = self.side + change
rectangle = Rectangle(5, 8)
square = Square(7)
print(rectangle.perimeter())
print(square.perimeter())
square.change_size(4)
print(square.perimeter())
class Shape():
def what_am_i(self):
print("I am a shape")
class Rectangle(Shape):
def __init__(self, l, w):
self.length = l
self.width = w
def perimeter(self):
return self.length * 2 + self.width * 2
class Square(Shape):
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
def change_size(self,change):
self.side = self.side + change
rectangle = Rectangle(5, 8)
square = Square(7)
rectangle.what_am_i()
square.what_am_i()
class Horse():
def __init__(self, age, sex, rider):
self.age = age
self.sex = sex
self.rider = rider
class Person():
def __init__(self, name):
self.name = name
jockey = Person("John")
horse = Horse(4, "M", jockey)
print(horse.rider.name)
|
8772205d0fc66508e33016b74e55cc9308d6c878 | madhuri-majety/IK | /binarysearch/binary_search_recursive_new.py | 926 | 3.984375 | 4 | #! /usr/bin/python
import time
def binary_search_rec(list, low, high, elem_to_find):
if low <= high:
mid = low + (high-low)//2
print("Printing mid {}". format(mid))
if list[mid] == elem_to_find:
return mid
elif elem_to_find < list[mid]:
return binary_search_rec(list, low, mid-1, elem_to_find)
else:
return binary_search_rec(list, mid+1, high, elem_to_find)
else:
return -1
input = int(input("Enter the number to search:"))
print("Number to search is {}". format(input) )
#list = [1,2,3,4,5,6,7,8,9]
list = [x for x in range(1,101)]
start_time = time.time()
result = binary_search_rec(list, 0, len(list)-1, input)
end_time = time.time()
print("Index is {}". format(result))
if( result >= 0 ):
print("Found the element")
else:
print("Not found the element")
print("Time took to search is {}". format(end_time - start_time))
|
871589099fa426e951b2aa3fc963ce0d36f94eb6 | patelamisha/SSW-567A | /HW01_triangle/Amisha_Patel_triangle_classification.py | 1,887 | 3.953125 | 4 | """ Author :: Amisha Patel
Created :: 02/06/2021
Assigment :: Testing triangle classification """
import unittest
def classifyTriangle(a,b,c):
"""This function returns a string with the type of triangle from three values
corresponding to the lengths of the three sides of the Triangle."""
if a <= 0 or b <= 0 or c <= 0:
return 'NotATriangle'
elif a == b and b == c:
return 'Equilateral'
elif (a**2 + b**2 == c**2) or (a**2 + c**2 == b**2) or (b**2 + c**2 == a**2):
return 'Right'
elif (a == b and a != c) or (b == c and b != a) or (a == c and a != b):
return 'Isoceles'
else :
return 'Scalene'
def runClassifyTriangle(a, b, c):
""" invoke classifyTriangle with the specified arguments and print the result """
print('classifyTriangle(', a, ',', b, ',', c, ')=', classifyTriangle(a, b, c),sep="")
class TestTriangles(unittest.TestCase):
def testSet1(self):
self.assertEqual(classifyTriangle(3, 4 ,5),'Right','3,4,5 is a Right triangle')
self.assertEqual(classifyTriangle(5, 3, 4), 'Right', '5, 3, 4 is a Right triangle')
self.assertEqual(classifyTriangle(3, 5, 4), 'Right', '3, 5, 4 is a Right triangle')
def testMyTestSet2(self):
self.assertEqual(classifyTriangle(0,2,3),'NotATriangle','should be a not a trianle')
self.assertEqual(classifyTriangle(1,1,1),'Equilateral','1,1,1 should be equilateral')
self.assertEqual(classifyTriangle(2, 3,5),'Scalene','Should be Isoceles')
self.assertNotEqual(classifyTriangle(0,1,1),'Isoceles','Should be Equilateral')
if __name__ == '__main__':
runClassifyTriangle(1, 2, 3)
runClassifyTriangle(1, 1, 1)
runClassifyTriangle(20, 20, 40)
runClassifyTriangle(5, 4, 3)
runClassifyTriangle(1, 1, 5)
runClassifyTriangle(-1,0, 0)
unittest.main(exit=False)
|
06e5ff66404ffd442b10555bd1ef8ef4391ec552 | mandamg/Exercicios-de-Python-do-Curso-em-Video | /Mundo 1/Aula 10/EX034-Aumento de Acordo com Salário.py | 174 | 3.734375 | 4 | s = float(input('Digite o salário: '))
if s>=1250:
print(f'Com o aumento seu salário passara a ser {s*1.10}')
else:
print(f'Seu novo salario séra de {s*1.15:.2f}') |
8ecaf43f8e141efff10858d00e323a43b83950c1 | Prabithapallat01/pythondjangoluminar | /oops/stud_oop.py | 468 | 3.8125 | 4 | class Students:
def set_Students(self,name,Course,rol):
self.name=name
self.course=Course
self.rol=rol
def print_Students(self):
# print("name=",self.name)
# print("Course=",self.course)
# print("age=",self.age)
print(self.name,",",self.course,",",self.rol)
obj=Students()
obj.set_Students("Aleena","MCA",27)
obj.print_Students()
obj1=Students()
obj1.set_Students("Maya","MCA",20)
obj1.print_Students()
|
b4b6cc55d39a4a7db47d8706cfcf6a44a89344d2 | trishinairyna/trishina | /lesson_9/9_3_trishina_irina.py | 875 | 4.28125 | 4 | # Задание 3
# Напишите функцию, которая отображает пустой или
# заполненный квадрат из некоторого символа. Функция
# принимает в качестве параметров: длину стороны ква-
# драта, символ и переменную логического типа:
# ■■ если она равна True, квадрат заполненный;
# ■■ если False, квадрат пустой.
def square_filling (a:int, symvol:str, b:bool):
if b==1:
for i in range(a):
print(symvol*a)
elif b==0:
for i in range(a):
if i==0 or i==a-1:
print(symvol * a)
else:
print(symvol+(a-2)*" "+symvol)
print(square_filling(5,"+",1))
print(square_filling(5,"-",0))
|
76648a0a63eccae1453622d4deb523aa4adfba86 | sakshigarg22/python-projects | /error.py | 309 | 3.78125 | 4 | ##rule 1
##try:
## pass
##except:
## pass
try:
int('ddsd')
except:
print('error handled')
while 1:
try:
i = int(input())
print(i)
break
except ValueError :
print('not valid integer...try again')
except EOF:
print('please enter something')
|
9ab1ab7ffb08d493d3df395b60883eaaeb047549 | annaleee/VG441 | /Homework/Homework1/codes/linear_regression.py | 1,875 | 3.546875 | 4 | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import pprint
from sklearn.datasets import load_boston
from sklearn import linear_model
from sklearn.model_selection import train_test_split
file = open("CALI.csv")
data=pd.read_csv(file,)
df_x = pd.DataFrame(data, columns = ['MedInc','HouseAge','AveRooms','AveBedrms','Population','AveOccup','Latitude','Longitude'])
df_y = pd.DataFrame(data,columns=['HOUSING PRICE'])
from statsmodels.api import OLS
model_LR = OLS(df_y, df_x).fit()
print(model_LR.summary())
x_train, x_test, y_train, y_test = train_test_split(df_x, df_y, test_size = 0.2, random_state = 4)
model = linear_model.LinearRegression()
model.fit(x_train,y_train)
results = model.predict(x_test)
print("Here is the example of testing value")
print(np.c_[y_test.values, results][0:5,:])
from sklearn.metrics import mean_squared_error, r2_score
model_score = model.score(x_train,y_train)
print('R2 sq: ', model_score)
# The mean squared error
print("Mean squared error: %.2f"% mean_squared_error(y_test, results))
# Explained variance score: 1 is perfect prediction
print('Test Variance score: %.2f' % r2_score(y_test, results))
pred_val = model_LR.fittedvalues.copy()
residual = pred_val - df_y.values.flatten()
fig, ax = plt.subplots(figsize=(6,2.5))
ax.scatter(residual, pred_val)
sns.distplot(residual)
import scipy as sp
fig, ax = plt.subplots(figsize=(6,2.5))
_, (__, ___, r) = sp.stats.probplot(residual, plot=ax, fit=True)
# Examining simple linear regression...
#X = df_x['CRIM'].values.reshape(-1, 1)
X = df_x.iloc[:,0].values.reshape(-1, 1)
#X = df_x['RM'].values.reshape(-1, 1)
#X = df_x.iloc[:,5].values.reshape(-1, 1)
Y = df_y.values.reshape(-1,1)
model3 = linear_model.LinearRegression()
model3.fit(X,Y)
Y_pred = model3.predict(X)
plt.scatter(X, Y)
plt.plot(X, Y_pred, color='red')
plt.show() |
325cc9e6ef1e818a7039b45b44b26c008a73c9e6 | wkwiatkowski/kurs-py | /exercises/w3resource/1.py | 445 | 3.53125 | 4 | #!/usr/bin/env python
a = """ Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are """
# print a
print ("Twinkle, twinkle, little star,\n\t How I wonder what you are!\n\t\t Up above the world so high,\n\t\t Like a diamond in the sky.\nTwinkle, twinkle, little star,\n\t How I wonder what you are")
|
22be7f1f3fd15fcc88e9e3d01ba716101c19f522 | sabhi14/PythonBasicsHandsOn | /assignment.py | 311 | 3.953125 | 4 | lengthOfList=int (input("Enter the length of list :- "))
list=[]
for i in range(lengthOfList) :
list.insert(i,int (input("Enter element in list:-")))
print(list)
sliceStart=int(input("Slice Start :- "))
sliceEnd=int(input("Slice End :- "))
list=list[sliceStart:sliceEnd]
list.sort()
print(list) |
e0b5d06cb3a3c287401a39c3d344f27acece5f87 | erbaclaire/Sample-Python-Code | /hw4/problem2.py | 3,888 | 3.859375 | 4 | '''
Homework 4 - Problem 2:
In this problem, we're going to continue exploring open data from the City of
Chicago, except this time we're going to take advantage of object-oriented
programming to build the foundation for a hypothetical "Chicago Public Schools
application". We have provided you with a CSV file with data on each public school
in Chicago including its name, location, address, what grades are taught, and what
network it is part of. You are asked to write three classes that will allow a user to
easily interact with this data.
See HW4 PDF for specifications
'''
# Checked work with Matt Pozsgai
import csv
import webbrowser
from math import sqrt, asin, cos, sin, radians, degrees
class School:
def __init__(self, data):
self.id = data['School_ID']
self.name = data['Short_Name']
self.network = data['Network']
self.address = data['Address']
self.zip = data['Zip']
self.phone = data['Phone']
self.grades = data['Grades'].split(',')
self.location = Coordinate.fromdegrees(float(data['Lat']), float(data['Long']))
def open_website(self):
webbrowser.open_new_tab("https://schoolinfo.cps.edu/schoolprofile/SchoolDetails.aspx?SchoolId={}".format(self.id))
def distance(self, coord):
return self.location.distance(coord)
def full_address(self):
return ("{}\nChicago, IL {}".format(self.address, self.zip))
def __repr__(self):
return "School({})".format(self.name)
class Coordinate:
def __init__(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
@classmethod # cite: https://www.geeksforgeeks.org/class-method-vs-static-method-python/
def fromdegrees(cls, latitude, longitude):
return cls(radians(latitude), radians(longitude))
def distance(self, coord):
return (2*3961*asin(sqrt(sin((self.latitude-coord.latitude)/2)**2 + cos(self.latitude)*cos(coord.latitude)*(sin((self.longitude-coord.longitude)/2)**2))))
def as_degrees(self):
return (degrees(self.latitude), degrees(self.longitude))
def show_map(self):
webbrowser.open_new_tab("http://maps.google.com/maps?q={},{}".format(self.as_degrees()[0],self.as_degrees()[1]))
def __repr__(self):
return "Coordinate{}".format(self.as_degrees())
class CPS:
def __init__(self, filename):
with open(filename, newline='') as f:
reader = csv.DictReader(f)
self.schools = []
for row in reader:
self.schools.append(School(row))
def nearby_schools(self, coord, radius = 1.0):
return [school for school in self.schools if school.distance(coord) < radius]
def get_schools_by_grade(self, *grades):
return [school for school in self.schools if len(set(map(lambda x: x.strip(), school.grades)) & set(grades)) == len(set(grades))]
def get_schools_by_network(self, network):
return [school for school in self.schools if school.network == network]
'''
if __name__ == '__main__':
cps = CPS('schools.csv')
print(cps.schools[:5])
print([s for s in cps.schools if s.name.startswith('OR')])
ace_tech = cps.schools[1]
print(ace_tech.name)
print(ace_tech.id)
print(ace_tech.network)
print(ace_tech.address)
print(ace_tech.zip)
print(ace_tech.full_address())
print(ace_tech.phone)
print(ace_tech.grades)
print(ace_tech.location)
print(ace_tech.location.as_degrees())
print(ace_tech.distance(cps.schools[77].location))
the_bean = Coordinate.fromdegrees(41.8821512, -87.6246838)
print(cps.nearby_schools(the_bean, radius=0.5))
print(cps.get_schools_by_grade('PK', '12'))
print(cps.get_schools_by_network('Contract'))
cics_ip = cps.schools[11]
cics_ip.open_website()
ace_tech.location.show_map()
'''
|
8520ec7e7cea92cd0920093856c4dd871a8a6124 | sahasatvik/assignments | /CS2201/assignment05/Q2.py | 543 | 3.671875 | 4 | #!/usr/bin/env python3
import pandas as pd
import matplotlib.pyplot as plt
marks = {'marksstu1': [60, 70, 80], 'marksstu2': [65, 75, 80], 'marksstu3': [70, 70, 90]}
n = len(marks)
df = pd.DataFrame(marks)
corr = df.corr()
x = []
y = []
# Generate the correlations for all unordered pairs
for i in range(n):
for j in range(i):
if i == j:
continue
x.append(str(j + 1) + '-' + str(i + 1))
y.append(corr.iloc[j, i])
plt.bar(x, y)
plt.xlabel("Marks/Student pairs")
plt.ylabel("Correlation")
plt.show()
|
b7297b4d704f3dada151fc6978845f2fc2d4665f | gabrielSSimoura/ListRemoveDuplicates | /main.py | 777 | 4.09375 | 4 | # Write a program (function!) that takes a list # and returns a new
# list that contains all the elements of the first list minus all the duplicates.
# Extras:
# Write two different functions to do this - one using a loop and constructing a list,
# and another using sets.
# Go back and do Exercise 5 using sets,
# and write the solution for that in a different function.
import random
def generateRandomList():
randomlist = []
for i in range(0, 20):
n = random.randint(1, 30)
randomlist.append(n)
return randomlist
def main():
randomList = generateRandomList()
print("Random List")
print(randomList)
randomList = set(randomList)
randomList = list(randomList)
print("Filtered List")
print(randomList)
main()
|
c04150caa174cb22f5677ec6939794fc87e21cf5 | MaxT2/EWIntroToPython | /Extras/Old Class Files/firstprograms/Numbers.py | 231 | 4 | 4 | x = int(input("What is x? "))
y = int(input("What is Y? "))
result1 = x + y
print ("x+Y = %d"%result1)
result1 = x - y
print ("x-Y = %d"%result1)
result1 = x * y
print ("x*Y = %d"%result1)
result1 = x / y
print ("x/Y = %d"%result1) |
1fca5444d6e0d7f98dec0d2bce4911d0ccc583aa | Priyankanettikallu/software-engineering-assignment | /version 1.4.py | 798 | 4.15625 | 4 | In [1]:
from math import sqrt
In [7]:
print("enter the values of a,b,c")
a=float(input())
b=float(input())
c=float(input())
d=(b*b)-(4*a*c)
if(a==0):
print("divide by zero error")
else:
if(d>0):
print("roots are real")
x1=(((-b)+sqrt(d))/(2*a))
x2=(((-b)-sqrt(d))/(2*a))
print("the roots are: %f and %f" %(x1,x2))
elif(d<0):
print("roots are imaginary")
x1=x2=(-b/(2*a))
j=(sqrt(-d))/(2*a)
print("x1= %.2f + %.2f i and x2= %.2f - %.2f i"%(x1,j,x2,j))
else:
print("roots are equal")
x1=x2=(-b/(2*a))
print("x1= %.2f and x2= %.2f "%(x1,x2))
enter the values of a,b,c
5
20
10
roots are real
the roots are: -0.585786 and -3.414214
->Extra Feature added...... ->option to enter inputs from keyboard |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.