blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c8af7a794f8074f9c803cd7ebb61ae00b509f475 | Frigus27/Structure-Iced | /iced/game_object.py | 2,130 | 4.1875 | 4 | """
game_object.py
--------------
The implement of the objects in the game.
The game object is the minimum unit to define a interactive
object in a game, e.g. a block, a road, a character, etc.
In Structure Iced, you can easily define an object by
simply inherit the class game_object. A game object
requires the arguments in the following text:
1. An image (which will be showed when game begins)
2. A creation function (To note what the function should do
when it is being created)
3. A loop function (To note what the function should do
every game loop)
4. A destroying function (The one when it is being
destroyed)
For more, see the documentation.
"""
import pygame
class Object():
"""The game object"""
class _InstanceVariables():
def __init__(self):
self.pos_x = 0
self.pos_y = 0
def __init__(self):
self.image = 0
self.image_surface = pygame.surface.Surface((0, 0))
self.InstanceVariables = self._InstanceVariables()
def set_image_by_filename(self, new_image_filename: str):
"""To set the image by filename and path"""
self.image = pygame.image.load(new_image_filename)
self.image_surface = self.image.convert()
def set_image_by_surface(self, new_image_surface: pygame.surface.Surface):
"""To set the image by the surface you've created"""
self.image = 0
self.image_surface = new_image_surface
def on_create(self):
"""the function executes when created"""
def loop(self):
"""the function executes every game loop"""
def on_destroy(self):
"""the function executes when destroyed"""
def update_instance_pos(self, new_pos_x: int, new_pos_y: int):
"""update the position of the instance of the object"""
self.InstanceVariables.pos_x = new_pos_x
self.InstanceVariables.pos_y = new_pos_y
def get_instance_pos(self):
"""get the position of the instance of the object"""
return self.InstanceVariables.pos_x, self.InstanceVariables.pos_y
| true |
c28d9ede48b5c683d129d8f18c93f823fe72be38 | artsyanka/October2016Test1 | /centralLimitTheorem-Outcomes-Lesson16.py | 1,088 | 4.125 | 4 | #Write a function flip that simulates flipping n fair coins.
#It should return a list representing the result of each flip as a 1 or 0
#To generate randomness, you can use the function random.random() to get
#a number between 0 or 1. Checking if it's less than 0.5 can help your
#transform it to be 0 or 1
import random
from math import sqrt
from plotting import *
def mean(data):
#print(float(sum(data))/len(data))
return float(sum(data))/len(data)
def variance(data):
mu=mean(data)
return sum([(x-mu)**2 for x in data])/len(data)
def stddev(data):
return sqrt(variance(data))
def flip(N):
#Insert your code here
flipsList=[]
for i in range(N):
if random.random() < 0.5:
flipsList.append(0)
else:
flipsList.append(1)
return flipsList
def sample(N):
#Insert your code here
meansList=[]
for i in range(N):
meansList.append(mean(flip(N)))
return meansList
N=1000
outcomes=sample(N)
histplot(outcomes,nbins=30)
print(mean(outcomes))
print(stddev(outcomes))
| true |
b579e7e4c50ed64154b48830b5d7e6b22c21dd64 | Rogerd97/mintic_class_examples | /P27/13-05-2021/ATM.py | 934 | 4.125 | 4 | # https://www.codechef.com/problems/HS08TEST
# Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction
# if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction
# (including bank charges). For each successful withdrawal the bank charges 0.50 $US.
# Calculate Pooja's account balance after an attempted transaction.
# Input:
# 30 120.00
# Output:
# 89.50
# Input:
# 42 120.00
# Output:
# 120.00
# Input:
# 300 120.00
# Output:
# 120.00
withdraw = float(input("Insert the withdraw: "))
balance = float(input("Insert the account's balance: "))
if withdraw % 5 != 0:
print("You should use numbers divided by 5")
elif balance > withdraw + 0.5:
new_balance = balance - (withdraw + 0.5)
print(f"Your new account balance is {new_balance}")
else:
print(f"You do not have enough money, your account balance is {balance}")
| true |
5ff84a677d4a9595a5d05185a7b0aecacea9e3dd | Rogerd97/mintic_class_examples | /P62/12-05-2021/if_else_2.py | 1,325 | 4.34375 | 4 | # Write a program that asks for the user for the month number
# your script should convert the number to the month's name and prints it
# Solution 1
# month_number = input("Insert a month number: ")
# month_number = int(month_number)
# months = {"1": "enero", "2": "febrero", "3": "marzo"}
# if month_number < 1 or month_number > 12:
# print("you inserted a not valid number")
# else:
# month = months[str(month_number)]
# print(month)
# # Solution 2
# month_number = input("Insert a month number: ")
# month_number = int(month_number)
# months = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre",
# "octubre", "noviembre", "diciembre"]
# # 0
# # 1
# if month_number < 1 or month_number > 12:
# print("you inserted a not valid number")
# else:
# month_number = month_number - 1
# print(months[month_number])
# # Solution 3
month_number = input("Insert a month number: ")
month_number = int(month_number)
months = ["", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre",
"octubre", "noviembre", "diciembre"]
# 1
# False and False
# False
# -1
# True and False
# False
if month_number < 1 or month_number > 12:
print("you inserted a not valid number")
else:
print(months[month_number])
| true |
ba2cf9d99471af4cd757d84a0716d02a1f32ca20 | Rogerd97/mintic_class_examples | /P27/25-05-2021/exercise_1.py | 989 | 4.5 | 4 | # Write a Python program to reverse a string
# Sample String : "1234abcd"
# Expected Output : "dcba4321"
# def <name> (<arg_1>, <arg_2>, ... <arg_n>):
# <algorithm>
# [optional] return <result>
def reverse_str(phrase):
result = phrase[::-1]
print(result)
# my_str = input("Inserte la frase: ")
# reverse_str(my_str)
# my_list = ["hola, frase 1","hola, frase 2", "hola, frase 3", "hola, frase 4"]
# for element in my_list:
# reverse_str(element)
# Solution 2
def reverseString(chain):
string_list = list(chain)
return ''.join(string_list[::-1])
print(reverseString(input()))
# Solution 3
Frase = str(input("Ingrese frase: "))
def reverse(Frase):
str = ""
for i in Frase:
str = i + str
return str
print("La cadena origin : " + Frase,end="")
print("La cadena invertida usando bucle: " + reverse(Frase), end="")
# hola mundo
# Iteration 1
# i ---> h
# str --> ""
# h + "" --> h
# Iteration 2
# i ---> o
# str --> "h"
# o + "h" --> oh
| false |
1c8ab3d7358c97399ee76c68896020d57f0a8a2a | Rogerd97/mintic_class_examples | /P27/12-05-2021/if_else_2.py | 1,801 | 4.5 | 4 | # Write a program that asks for the user for the month number
# your script should convert the number to the month's name and prints it
# month_number = input("Insert a month number: ")
# month_number = float(month_number)
# Solution 1
num= float(input("Ingrese el numero del mes : "))
# if num == 1:
# print("Mes de Enero")
# elif num == 2:
# print("Mes de Febrero")
# elif num == 3:
# print("Mes de Marzo")
# elif num == 4:
# print("Mes de Abril")
# elif num == 5:
# print("Mes de Mayo")
# elif num == 6:
# print("Mes de Junio")
# elif num == 7:
# print("Mes de Julio")
# elif num == 8:
# print("Mes de Agosto")
# elif num == 9:
# print("Mes de Septiembre")
# elif num == 10:
# print("Mes de Octubre")
# elif num == 11:
# print("Mes de Noviembre")
# elif num == 12:
# print("Mes de Diciembre")
# else:
# print("Error número ingresado")
# Solution 2
# if num not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]:
# print("No valido")
# elif num == 1:
# print("Mes de Enero")
# elif num == 2:
# print("Mes de Febrero")
# Solution 3
# if num in range(1, 13):
# print("No valido")
# elif num ==1:
# print("Enero")
# .
# .
# .
my_dict = {1: "enero", 2: "febrero"}
if num not in range(1, 13):
print("No es valido")
else:
print(my_dict[num])
# Solution 4
indexes = list(my_dict.keys())
if num not in indexes:
print("No valido")
else:
print(my_dict[num])
# Solution 5
month = ['','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
n = input("Insert a number: ")
n = int(n)
if n < 0 and n > 12:
print("Inserte un numero valido")
else:
if n in range(1,12):
print(month[n])
else:
print("Error")
| false |
3b41d3051d166653385c7072bab3f1fc7bb3e462 | Rogerd97/mintic_class_examples | /P62/26-05-2021/exercise_1.py | 540 | 4.46875 | 4 | # Write a Python script to display the various Date Time formats
# a) Current date and time
# b) Current year
# c) Month of year
# d) Week number of the year
# e) Weekday of the week
# f) Day of year
# g) Day of the month
# h) Day of week
import datetime
def print_dates():
date = datetime.datetime.now()
print(date)
print(date.year)
print(date.month)
print(date.strftime("%b"))
print(date.strftime("%U"))
print(date.strftime("%j"))
print(date.strftime("%d"))
print(date.strftime("%A"))
print_dates()
| true |
7d23f66decf7741002378f7895a5b49dd7d65d6c | Rogerd97/mintic_class_examples | /P47/26-05-2021/exercise_1.py | 489 | 4.40625 | 4 | # Write a Python script to display the various Date Time formats
# a) Current date and time
# b) Current year
# c) Month of year
# d) Week number of the year
# e) Weekday of the week
# f) Day of year
# g) Day of the month
# h) Day of week
import datetime
#a)
date=datetime.datetime.now()
print(date)
#b)
print(date.year)
#c)
print(date.month)
#d
print(date.strftime("%U"))
#e)
print(date.strftime("%W"))
#f)
print(date.strftime("%j"))
#g)
print(date.day)
#h)
print(date.strftime("%A"))
| false |
9d386d7dece46d9e947ae02c509e0ff10fa08be5 | levi-fivecoat/Learn | /datatypes/strings.py | 473 | 4.28125 | 4 | my_str = "This is a string."
my_str_2 = "I am a strings. I can contain numbers 12345"
my_str_3 = "1390840938095"
username = "levi : "
# YOU CAN ADD STRINGS
my_str = username + my_str
my_str_2 = username + my_str_2
# YOU CAN SEE WHAT KIND OF DATA TYPE BY USING TYPE()
print(type(my_str))
# UPPERCASES STRING
my_str = my_str.upper()
# CAPITALIZES FIRST LETTER
print(my_str.capitalize())
# YOU CAN PRINT BY USING PRINT()
print(my_str)
print(my_str_2)
print(my_str_3)
| true |
1ec283d625a9d3c85d2800635f7fc2b6ab4adf7e | hklhai/python-study | /coll/tupleTest.py | 552 | 4.125 | 4 | # coding=utf-8
# 元组是不可变对象,元组支持嵌套
# 列表使用场景频繁修改的情况,元组对于不修改仅查询使用,查询效率高
a = (1, 2, "22")
print(type(a))
for e in a:
print(e)
b = [x for x in a]
print(b)
# 生成器
b = (x for x in a)
print(b)
print(b.next())
print(b.next())
print(b.next())
# 元组的索引操作
print(a[1])
# 格式化输出字符串
print('abcd %d and %s' % (66, "hello"))
b = ([1, 2, 3], 2)
print(type(b))
print(b)
# 修改元组内的嵌套列表
a = b[0]
a.append("s")
print(b)
| false |
aa878f2bfc544a6ffdb642d6279faba0addc552c | Juxhen/Data14Python | /Introduction/hello_variables.py | 1,333 | 4.25 | 4 | # a = 5
# b = 2
# c = "Hello!"
# d = 0.25
# e = True
# f = [1,2,3]
# g = (1,2,3)
# h = {1,2,3}
#
# print(a)
# print(b)
# print(c)
#
# # How to find the type of variables
# print(type(a))
# print(type(b))
# print(type(c))
# print(type(d))
# print(type(e))
# print(type(f))
# print(type(g))
# print(type(h))
# CTRL + / To comment out a block of code
# print("What is your name?")
# name = input()
# print(name)
# Use input to collect name, age and DOB from user & display them
#
# print("What is your name?")
# name = input()
# nameType = type(name)
# print("What is your age?")
# age = input()
# ageType = type(age)
# print("What is your d.o.b, format DD/MM/YY")
# dob = input()
# dobType = type(dob)
# print(name, age, dob)
# print(dobType)
#
#-----------------------------------------------------------------------
#
# name = input("What is your name?")
# age = int(input("What is your age")) #casting change one data type to another
# age = int(input("Siblings"))
# decimal = float(print("Favourite decimal"))
# animal = input("what is your fav animal")
#
# print(f"Hi {name} you're {age} and you have {siblings} your fav dec is {decimal} and your fav animal is {animal}")
#-------boolean ---------------
hw = "Hello World!"
hw.isalpha()
print(hw.islower())
print(hw.isupper())
print(hw.startswith("H"))
print(hw.endswith("!")) | true |
2869ab5cc0f73d29fb120418cd2dcb7f5ab41867 | CrunchyPistacho/Algorithms | /data_structures/stack.py | 1,760 | 4.125 | 4 | class Stack:
def __init__(self, Size = 5):
self.__size = Size
self.__stack = []
self.__i = -1
def is_empty(self):
if len(self.__stack) == 0:
return(0)
def is_full(self):
if len(self.__stack) == self.__size:
return(len(self.__stack))
def push(self, value):
if self.is_full():
raise IndexError("Stack is full - Overflow Error")
else:
self.__stack.append(value)
def pop(self):
if self.is_empty():
raise IndexError("Stack is empty - Underflow Error")
else:
return(self.__stack.pop())
def __len__(self):
return(len(self.__stack))
def __getitem__(self,index):
if index < len(self):
return(self.__stack[index])
else:
raise(IndexError("Index out of range"))
def __previous__(self):
self.__i -= 1
if self.__i >= len(self):
return(self.__stack[self.__i])
else:
raise StopIteration("First item reached")
def __next__(self):
self.__i += 1
if self.__i < len(self):
return(self.__stack[self.__i])
else:
raise StopIteration("Last item reached")
def __iter__(self):
self.__i = -1
return(self)
def __str__(self):
Values = []
for i in self.__stack:
Values.append(str(i))
return ", ".join(Values)
if __name__ == '__main__':
S1 = Stack(3)
for i in range(3):
print("Insert", i, "in stack")
S1.push(i)
print("Stack : ", end="")
for i in S1:
print(i, end=", ")
print("Pop, popped element = ", S1.pop())
print("Stack :", S1)
| false |
c4b2d02cb02ff875450fc56f1b839cab49b85af6 | SDBranka/A_Basic_PyGame_Program | /hello_game.py | 718 | 4.15625 | 4 | #Import and initialize Pygame library
import pygame
pygame.init()
#set up your display window
screen = pygame.display.set_mode((500,500))
#set up a game loop
running = True
while running:
# did user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# fill the screen with white
white_for_screenfill = (255,255,255)
screen.fill(white_for_screenfill)
# draw a solid blue circle
blue_for_circle = (0,0,255)
location_of_circle_center = (250,250)
pygame.draw.circle(screen, blue_for_circle, location_of_circle_center, 75)
#flip the display
pygame.display.flip()
#exit pygame
pygame.quit() | true |
67cf549f5e3ad4935427432d9561de90a1b5e0c7 | lauram15a/Fundamentos_de_programacion | /CUADERNOS DE TRABAJO/CUADERNO 5/ej 6 cuaderno 5 cuadrado.py | 2,923 | 4.1875 | 4 | #Laura Mambrilla Moreno
#Ej 6 cuaderno 5
"""
Implementa una estructura “Cuadrado” que incluya información sobre sus 4
vértices y sobre su punto central, todos los cuales seran del tipo Punto2D.
"""
#librerías
import math
#funciones
class Punto2D :
def __init__ (self, x, y):
self.x = x
self.y = y
class Cuadrado :
def __init__ (self, v1, v2, v3, v4, centro):
self.v1 = v1
self.v2 = v2
self.v3 = v3
self.v4 = v4
self.centro = centro
def crear_punto ():
"""
nada --> float, float
OBJ: crear punto
"""
x = float(input('\nx = '))
y = float(input('y = '))
punto = Punto2D(x, y)
return punto
def crear_cuadrado ():
"""
nada --> float, float, float, float
OBJ: crear cuadrado
"""
print('\n Vértice 1: ')
v1 = crear_punto ()
print('\n Vértice 2: ')
v2 = crear_punto ()
print('\n Vértice 3: ')
v3 = crear_punto ()
print('\n Vértice 4: ')
v4 = crear_punto ()
#calculamos centro
x = (v4.x + v3.x)/2
y = (v1.y + v3.y)/2
centro = Punto2D(x, y)
cuadrado = Cuadrado (v1, v2, v3, v4, centro)
return cuadrado
def calcular_distancia (punto1, punto2):
"""
float, float --> float
OBJ: calcular la distancia entre 2 puntos
"""
d = math.sqrt((punto2.x - punto1.x)**2 + (punto2.y - punto1.y)**2)
return d
def comprobar_cuadrado (cuadrado):
"""
float --> bool
OBJ: comprobar que los datos introducidos forman un cuadrado
"""
#lados
#v1 y v2
d12 = calcular_distancia (cuadrado.v1, cuadrado.v2)
#v1 y v3
d31 = calcular_distancia (cuadrado.v3, cuadrado.v1)
#v2 y v4
d42 = calcular_distancia (cuadrado.v4, cuadrado.v2)
#v3 y v4
d34 = calcular_distancia (cuadrado.v3, cuadrado.v4)
#diagonales
#v1 y v4
d14 = calcular_distancia (cuadrado.v1, cuadrado.v4)
#v2 y v3
d23 = calcular_distancia (cuadrado.v2, cuadrado.v3)
#comprobamos
return d12 == d31 and d31 == d42 and d42 == d34 and d14 == d23
def mostrar_cuadrado (cuadrado):
"""
float --> float
OBJ: imprimir las coordenadas del cuadrado
"""
print('\n COORDENADAS CUADRADO:')
print ('v1 = (', cuadrado.v1.x,',',cuadrado.v1.y,')')
print ('v2 = (', cuadrado.v2.x,',',cuadrado.v2.y,')')
print ('v3 = (', cuadrado.v3.x,',',cuadrado.v3.y,')')
print ('v4 = (', cuadrado.v4.x,',',cuadrado.v4.y,')')
print ('centro = (', cuadrado.centro.x,',',cuadrado.centro.y,')')
#main
print ('\n v1-----------v2')
print (' | |')
print (' | |')
print (' | |')
print (' | |')
print (' | |')
print (' | |')
print (' v3-----------v4 ')
cuadrado = crear_cuadrado ()
if comprobar_cuadrado(cuadrado) == True:
mostrar_cuadrado (cuadrado)
else:
print('\nNo es un cuadrado.')
| false |
6bdba93386d8b4f5b4d6662a0f6d774ea195792f | lauram15a/Fundamentos_de_programacion | /CUADERNOS DE TRABAJO/CUADERNO 3/ej 16 cuaderno 3 serie armónica.py | 1,837 | 4.125 | 4 | #LAURA MAMBRILLA MORENO
#EJ 16 CUADERNO 3
"""
. Escribe un programa que pida un número límite y calcule cuántos términos de la
serie armónica son necesarios para que su suma supere dicho límite. Es decir,
dado un límite introducido por el usuario (por ejemplo 50) se trata de determinar
el menor número n tal que:
1 + 1/2 + 1/3 + 1/n > limite
En nuestro ejemplo, para un límite = 5, n sería 83. El programa ha de ser
robusto, es decir, ha de controlar que el número introducido por el usuario es un
entero positivo.
"""
def validacion_entero(entero):
"""
float --> bool
OBJ: Validar si el dato introducido por el usuario es un número entero
"""
try:
dato = int(entero)
if entero > 0:
validacion = True
else:
validacion = False
except:
print ('El dato introducido no es entero.')
validacion = False
return validacion
def leer_entero_validado():
"""
nada --> int
OBJ: Solicita un entero al usuario, lo valida y lo retorna sólo cuando se ha asegurado de que es realmente un entero
"""
entero = int(input('Introduzca un número entero: '))
valido_entero = validacion_entero(entero)
while valido_entero == False:
entero = input('Introduzca un número entero positivo: ')
valido_entero = validacion_entero(entero)
return entero
def terminos (entero):
"""
int --> int
OBJ: pedir un número límite y calcule cuántos términos de la serie armónica son necesarios para que su suma supere dicho límite.
"""
vueltas = 0 #vueltas = i
suma = 0
while suma < entero:
vueltas = vueltas + 1
suma = suma + 1/vueltas
return vueltas
#main
entero = leer_entero_validado()
print ('Son necesarios ', terminos (entero), 'términos para completar la serie armónica')
| false |
fc819bc1fd471c362999ea00a80e78c87c84973b | lauram15a/Fundamentos_de_programacion | /CUADERNOS DE TRABAJO/CUADERNO 2/ej 13 cuaderno 2 distancia puntos.py | 818 | 4.28125 | 4 |
#Ejercicio 13 - Cuaderno 2
#Escribe una función que a partir de las coordenadas 3D de dos puntos en el espacio en formato (x, y, z) calcule la distancia que hay entre dichos puntos.Prueba su función y el resultado por pantalla.
import math
def distancia (xA, yA, zA, xB, yB, zB):
"""
float, float, float ---> float
OBJ: calcular la distancia entre 2 puntos en el espacio
"""
distancia = math.sqrt ((xB - xA)**2 + (yB - yA)**2 + (zB - zA)**2)
return distancia
#PROBADOR
print ('Punto A')
xA = float (input( 'x = '))
yA = float (input( 'y = '))
zA = float (input( 'z = '))
print (' ')
print ('Punto B')
xB = float (input( 'x = '))
yB = float (input( 'y = '))
zB = float (input( 'z = '))
print (' ')
print ('Distancia entre A y B = ', distancia (xA, yA, zA, xB, yB, zB), ' unidades')
| false |
77eb5d2baa36b9b114940e8e7b9b8ae86ea36e60 | lauram15a/Fundamentos_de_programacion | /CUADERNOS DE TRABAJO/CUADERNO 5/ej 5 cuaderno 5 distancia.py | 859 | 4.21875 | 4 | #Laura Mambrilla Moreno
#Ej 5 cuaderno 5
"""
Programa una función distancia_2D que calcule la distancia entre dos
puntos. La función retornará un número real según la siguiente fórmula:
d=((x2 - x1)**2 + (y2 + y1)**2)**(1/2)
"""
#librerías
import math
#funciones
class Punto2D :
def __init__ (self, x, y):
self.x = x
self.y = y
def crear_punto ():
"""
nada --> float, float
OBJ: crear punto
"""
x = float(input('\nx = '))
y = float(input('y = '))
punto = Punto2D(x, y)
return punto
def distancia (punto1, punto2):
"""
float, float --> float
OBJ: calcular la distancia entre 2 puntos
"""
d = math.sqrt((punto2.x - punto1.x)**2 + (punto2.y - punto1.y)**2)
return d
#main
punto1 = crear_punto()
punto2 = crear_punto()
print('\nLa distancia es de %d unidad(es).'%distancia(punto1, punto2))
| false |
6e20e66735834d1dd5b8f94ecc6f091ee171374d | lauram15a/Fundamentos_de_programacion | /CUADERNOS DE TRABAJO/CUADERNO 3/ej 10 cuaderno 3 del 1 al 12 meses.py | 1,803 | 4.3125 | 4 | #LAURA MAMBRILLA MORENO
#EJ 10 CUADERNO 3
""""
Codifica un subprograma que reciba un número entero, y si es entre 1 y 12
escriba un mensaje por pantalla indicando el mes a que dicho número
corresponde. En caso contrario deberá mostrar un mensaje de error. Valida las
entradas utilizando la función del ejercicio 9.
"""
def validacion_entero(entero):
"""float -> bool
OBJ: Validar si el dato introducido por el usuario es un numero entero"""
try:
elem = int(entero)
validacion = True
except:
print("El dato introducido no es un numero entero.")
validacion = False
return validacion
def leer_entero_validado():
"""nada -> int
OBJ: Solicita un entero al usuario, lo valida y lo retorna sólo cuando se ha asegurado de que es realmente un entero
"""
entero = input("Introduzca un numero entero: ")
valido_entero = validacion_entero(entero)
while valido_entero == False:
entero = input("Introduzca un numero entero: ")
valido_entero = validacion_entero(entero)
return entero
entero = leer_entero_validado()
if entero == '1' :
print('El mes es Enero')
elif entero == '2' :
print ('El mes es Febrero')
elif entero == '3' :
print ('El mes es Marzo')
elif entero == '4' :
print ('El mes es Abril')
elif entero == '5' :
print ('El mes es Mayo')
elif entero == '6' :
print ('El mes es Junio')
elif entero == '7' :
print ('El mes es Julio')
elif entero == '8' :
print ('El mes es Agosto')
elif entero == '9' :
print ('El mes es Septiembre')
elif entero == '10' :
print ('El mes es Octubre')
elif entero == '11' :
print ('El mes es Noviembre')
elif entero == '12' :
print ('El mes es Diciembre')
else:
print ('Error, el entero introducido no corresponde a ningun mes')
| false |
ddd140fff48bea6af7ba893bfb4b64c5e4bff904 | mtjhartley/data_structures | /pre_vertafore/old_python/reverse_list.py | 297 | 4.125 | 4 | test1 = [3,1,6,4,2]
test2 = [3,1,6,4]
def reverse_list(arr):
end = len(arr) - 1
for idx in range(len(arr)/2):
temp = arr[idx]
arr[idx] = arr[end-idx]
arr[end-idx] = temp
#print arr
return arr
print reverse_list(test1)
print reverse_list(test2)
| false |
311fba0777ef7a120c51436743d9ceb3e0fd3470 | ArseniyCool/Python-YandexLyceum2019-2021 | /Основы программирования Python/4. While-loop/Скидки!.py | 550 | 4.125 | 4 | # Программ считает сумму товаров и делает скидку 5 % на товар,если его стоимость превышает 1000
price = float(input('Введите цену на товар:'))
cost = 0
while price >= 0:
if price > 1000:
cost = cost + (price - 0.05 * price)
else:
cost = cost + price
price = float(input('Введите цену на товар:'))
# Сигнал остановки - нуль или отрицательное число
print(cost)
| false |
0c8643ec77ec3a9702da7e8202650f7b70c2f486 | ArseniyCool/Python-YandexLyceum2019-2021 | /Основы программирования Python/9. Sets/Книги на лето.py | 984 | 4.125 | 4 | # Представьте, что Вам задали читать книги на лето
# К счастью, у Вас на компьютере есть текстовый документ, в котором записаны
# все книги из его домашней библиотеки в случайном порядке.
# Программа определяет, какие книги из списка на лето у Вас есть, а каких нет.
M = int(input('Введите кол-во книг на Вашем компьютере:'))
N = int(input('Введите кол-во книг на лето:'))
library = set()
# Вводите названия книг согласно их количеству
for i in range(M):
book = input()
library.add(book)
for i in range(N):
spisok = set()
book = input()
spisok.add(book)
if spisok <= library:
print('Есть')
else:
print('Нет')
| false |
c19f01337bf12fea45fd094be225f74ef3625d28 | ArseniyCool/Python-YandexLyceum2019-2021 | /Основы программирования Python/10. Strings indexing/Игра в города — Альфа.py | 612 | 4.28125 | 4 | # Игра в города в один раунд:
# Участники вводят поочередно 2 города(1 раз),
# так чтобы каждая начальная буква города начиналась с конечной буквы прошлого города,
# если второй участник ошибётся - он проиграет
#
# Города писать в нижнем регистре
word_1 = input()
word_2 = input()
if word_1[len(word_1) - 1] == word_2[0]:
print('В разработке...')
else:
print('Вы проиграли!')
| false |
fc89779a2cf480512ac48b7a21c5d344a30e56d6 | Seanie96/ProjectEuler | /python/src/Problem_4.py | 1,154 | 4.34375 | 4 | """ solution to problem 4 """
NUM = 998001.0
def main():
""" main function """
starting_num = NUM
while starting_num > 0.0:
num = int(starting_num)
if palindrome(num):
print "palindrome: " + str(num)
if two_factors(num):
print "largest number: " + str(num)
return 0
starting_num = starting_num - 1.0
return 0
def palindrome(num):
""" checkes whether the passed number is a palindrome """
num_str = str(num)
index = 0
length = len(num_str)
while index <= (length / 2):
if num_str[index] != num_str[length - 1 - index]:
return False
index = index + 1
return True
def two_factors(num_1):
""" Function that discoveres whether the passed number can be
broken down into 2 three digit number factors. """
num_1 = float(num_1)
index = 100.0
while index < num_1 and index < 1000.0:
num_2 = num_1 / index
if num_2 % 1.0 == 0 and num_2 >= 100.0 and num_2 < 1000.0:
return True
index = index + 1.0
return False
if __name__ == "__main__":
main()
| true |
95eb8f40f40eed4eebfa1e13dcb0117b80cb6832 | mamare-matc/Intro_to_pyhton2021 | /week3_strings.py | 1,347 | 4.5 | 4 | #!/usr/bin/python3
#week 3 srting formating assignment
varRed = "Red"
varGreen = "Green"
varBlue = "Blue"
varName = "Timmy"
varLoot = 10.4516295
# 1 print a formatted version of varName
print(f"'Hello {varName}")
# 2 print multiple strings connecting with hyphon
print(f"'{varRed}-{varGreen}-{varBlue}'")
# 3 print strings concatnating with variable
print(f"'Is this {varGreen} or {varBlue}?'")
# 4 print string concatnating with varName
print(f"'My name is {varName}'")
# 5 print varRed by adding ++
print(f"'[++{varRed}++]'")
# 6 print varGreen adding == at the end
print(f"'[{varGreen.lower()}==]'")
# 7 print **** and varBlue
print(f"'[****{varBlue.lower()}]'")
# 8 print varBlue multiple time
print(f"'{varBlue}'"*10)
# 9 print varLoot with single qoute
print(f"'{varLoot}'")
# 10 print varLoot using indexing to get the first three numbers
print(round(varLoot, 1))
# 11 print string concat with indexing varLoot
print(f"I have $" + str(round(varLoot, 2)))
# 12 print a formatted string that contais variables
print(f"'[$$${varRed}$$$$][$${varGreen}$$$][$$${varBlue}$$$]'")
# 13 print reversed string for varRed and varBlue
print(f"'[ {varRed[::-1]} ][ {varGreen} ][ {varBlue[::-1]} ]'")
# 14 print string concattnating with variables
print(f"'First Color:[{varRed}]Second Color:[{varGreen}]Third Color:[{varBlue}]'")
| true |
cd21e893b48d106b791d822b6fded66542924661 | a12590/LeetCode_My | /100-149/link_preoder(stack)_flatten.py | 1,798 | 4.1875 | 4 | #!/usr/bin/python
# _*_ coding: utf-8 _*_
"""
非递归先序遍历,注意rtype void要求
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
# pointer
pointer = TreeNode(None)
if root is None:
return
stack = []
stack.append(root)
while stack:
top = stack.pop()
# 这里先遍历right是因为stack,使得出栈left先
if top.right:
stack.append(top.right)
if top.left:
stack.append(top.left)
pointer.right = top
pointer.left = None
pointer = top
# 全局dummy
# self.pointer = None
# def traverse(root):
# if not root:return
# # 后序遍历
# traverse(root.right)
# traverse(root.left)
# root.left = self.pointer
# root.left = None
# self.pointer = root
# traverse(root)
"""
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public TreeNode parentNode = null;
public void flatten(TreeNode root) {
if (root == null){
return;
}
if (parentNode != null){
parentNode.left = null;
parentNode.right = root;
}
# 后移不是next,而是后赋值前
parentNode = root;
flatten(root.left);
flatten(root.right);
}
}
"""
| true |
56db6680ee71ac028d80721be24dff5e9c844f06 | BrunoPessi/lista-exercicios-python | /ex7.py | 897 | 4.1875 | 4 | # 7 - Escreva um algoritmo que leia 10 números informados pelo usuário e, depois, informe o menor, número,
# o maior número, a soma dos números informados e a média aritmética dos números informados.
def maior (numeros):
print("O maior numero digitado foi:",max(numeros))
def menor (numeros):
print("O menor numero digitado foi:",min(numeros))
def soma(numeros):
soma_elementos = 0
for num in numeros:
soma_elementos += num
print("A soma dos numeros digitados é:", soma_elementos)
def media(numeros):
soma_elementos = 0
for num in numeros:
soma_elementos += num
media_elementos = soma_elementos/len(numeros)
print("A media dos numeros digitados é:", media_elementos)
numeros = []
for i in range(0, 9):
num = int(input("Digite um numero"))
numeros.append(num)
maior(numeros)
menor(numeros)
soma(numeros)
media(numeros) | false |
8002e75ad6a2bddaf3ce57ca4a82e16bf0353339 | BrunoPessi/lista-exercicios-python | /ex3.py | 699 | 4.21875 | 4 | # 3 - Crie uma classe calculadora com as quatro operações básicas (soma, subtração, multiplicação e divisão). O
# usuário deve informar dois números e o programa deve fazer as quatro operações. (modifique para calcular tudo no
# mesmo método, somando 1 ao resultado de cada operação).
def calculadora (n1,n2):
soma = (n1+n2) + 1
subtrair = (n1-n2) + 1
multiplicacao = (n1*n2) + 1
divisao = (n1/n2) + 1
print("\n Soma: ", soma)
print("\n Subrtração: ", subtrair)
print("\n Multiplicacão: ", multiplicacao)
print("\n Divisão: ", divisao)
n1 = int(input("Digite o primero numero"))
n2 = int(input("Digite o segundo numero"))
calculadora(n1,n2)
| false |
9f12786f688abb908c333b2249be6fb18bdcd1d6 | keyurbsq/Consultadd | /Additional Task/ex6.py | 258 | 4.4375 | 4 | #Write a program in Python to iterate through the string “hello my name is abcde” and print the
#string which is having an even length.
k = 'hello my name is abcde'
p = k.split(" ")
print(p)
for i in p:
if len(i) % 2 == 0:
print(i)
| true |
d63d46c893052f76ea6f0906dd7166af5793a27b | keyurbsq/Consultadd | /Additional Task/ex4.py | 245 | 4.3125 | 4 | #Write a program in Python to iterate through the list of numbers in the range of 1,100 and print
#the number which is divisible by 3 and is a multiple of 2.
a = range(1, 101)
for i in a:
if i%3 == 0 and i%2==0:
print(i)
| true |
da83ffdd1873d70f4f5321c09c0a3ff1fb1ffc85 | r0meroh/CSE_CLUB_cpp_to_python_workshop | /people_main.py | 1,580 | 4.25 | 4 | from person import *
from worker import *
import functions as fun
def main():
# create list of both types of objects
people = []
workers = []
# prompt user
answer = input("adding a Person, worker? Or type exit to stop\n")
answer = answer.upper()
while answer != 'EXIT':
# if anwer is person, create a person object and append it to list
if answer == 'PERSON':
name = input('Enter name of person:\n')
age = input('Enter age of person:\n')
name = person(name, age)
people.append(name)
print('the following person was added:' )
fun.display_person(name)
elif answer == 'WORKER':
name = input('Enter name of worker\n:')
age = input('Enter age of worker: \n')
occupation = input('Enter occupation of worker: ')
name = worker(name,age,occupation)
workers.append(name)
print('the following worker was added: ')
fun.display_worker(name)
else:
print('invalid choice, please try again...\n')
answer = input("adding a Person, worker? Or type exit to stop\n")
answer = answer.upper()
# outside of loop
return people, workers
def print_lists(list):
for item in list:
print(item)
if __name__ == '__main__':
list_of_people, list_of_workers = main()
print('The following people were added:')
print_lists(list_of_people)
print('The following workers were added: ')
print_lists(list_of_workers)
| true |
e0058dfbb608836b24d131f6c92cabc1c551ad68 | rjraiyani/Repository2 | /larger_number.py | 272 | 4.125 | 4 | number1 = int(input('Please enter a number ' ))
number2 = int(input('Please enter another number ' ))
if number1 > number2:
print('The first number is larger.')
elif number1 < number2:
print('The second number is larger.')
else:
print('The two numbers are equal.' )
| true |
84b13b5ca2d438daac8c08a6a4d339f0ee9eb653 | rjraiyani/Repository2 | /exercise2.py | 266 | 4.375 | 4 | x = int(input('Please enter a number '))
m = x % 2
n = x % 3
if m == 0: #Even number
if n == 0:
print('Even and Divisible by 2')
else:
print('Even')
else:
if n == 0:
print('odd and divisible by 3')
else:
print('odd')
| false |
837e57d5a2751f378a6d51770a219754400b7197 | Andchenn/Lshi | /day02/集合.py | 1,021 | 4.21875 | 4 | # 集合:以大括号形式表现的数据集合,集合里面的数据不可以重复
# 集合可以根据下标获取数据,也可以添加和删除
# 不可以以此种方式定义空的集合
# my_set = {} #dict字典
my_set = {1, 4, "abc", "张三"}
print(my_set)
# 删除数据(删除指定数据)(不能删除没有的数据)
# my_set.remove("22")
# print(my_set)
# 增加数据
# 不可以添加重复的数据
my_set.add("5")
my_set.add("5")
my_set.add("5")
print(my_set)
# 删除集合里面的数据(删除没有的数据不会崩溃)
# my_set.discard(12222)
# print(my_set)
# 根据下标修改数据(集合是无序的)
# my_set[0] = 2
# print(my_set)
# 取出数据容器里面的每一个元素,就是遍历
for value in my_set:
print(value)
# 定义一个空集合
my_set = set()
print(my_set, type(my_set))
my_set.add("a")
my_set.add(123)
my_set.add(11)
print(my_set)
# 作业:
# 将集合转换成列表,元组(三种数据容器类型相互转换)
# tuple() list() set()
| false |
edd5cf21f14675cf6a4af3d6f20a082bd48ab1ae | davidlkang/foundations_code | /shopping_list.py | 1,423 | 4.125 | 4 | def show_help():
print("""
Type 'HELP' for this help.
Type 'CLEAR' to clear your list.
Type 'DEL X' where 'X' is the number of the element you want to remove.
Type 'SHOW' to display your list.
Type 'DONE' to stop adding items.
""")
def add_to_list(user_input):
shopping_list.append(user_input.lower())
print("Great! Your item was added. There are", len(shopping_list), "items in your list.")
def clear_list():
shopping_list.clear()
print("Success. Your list was cleared.")
def show_list():
print("You have the following items in your shopping list: ")
for element in shopping_list:
print(element)
def delete_item_from_list(index):
index = int(index) - 1
print("You succesfully removed {}.".format(shopping_list.pop(index)))
shopping_list = []
show_help()
while True:
user_input = input("> ")
if user_input == "HELP":
show_help()
elif user_input == "CLEAR":
clear_list()
elif "DEL " in user_input:
delete_item_from_list(user_input[4])
elif user_input == "SHOW":
show_list()
elif user_input == "DONE":
show_list()
break
elif user_input.lower() in shopping_list:
print("You already have {} in your shopping list. Do you still want to add it? ".format(user_input))
if input("(Y/N) ").lower() == "y":
add_to_list(user_input)
else:
add_to_list(user_input)
| true |
7ca179a45c2136eb638a635b700909482a5376fb | davidlkang/foundations_code | /login_app.py | 1,277 | 4.25 | 4 | users = {
"user1" : "password1",
"user2" : "password2",
"user3" : "password3"}
def accept_login(users, username, password):
if username in users:
if password == users[username]:
return True
return False
def login():
while True:
if input("Do you want to sign in?\n(Y/n) ").lower() == "y":
username = input("What is your username? ")
password = input("And your password? ")
if accept_login(users, username, password):
print("login successful!")
break
else:
print("login failed...")
else:
if input("Do you want to sign up?\n(Y/n) ").lower() == "y":
username_input = input("Please enter your username.\n> ")
while username_input in users:
username_input = input("Please use another username!\n> ")
password_input = input("Great! That username works. Now enter your password!\n> ")
users.update({username_input: password_input})
print("Your username: {} was added.".format(username_input))
else:
print("Goodbye!")
break
if __name__ == "__main__":
login()
| true |
f02e6f8d9a81b072ab3582f1469a62cc25b0905b | takaakit/design-pattern-examples-in-python | /structural_patterns/flyweight/main.py | 901 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from structural_patterns.flyweight.large_size_string import LargeSizeString
'''
Display a string consisting of large characters (0-9 digits only).
Large character objects are not created until they are needed.
And the created objects are reused.
Example Output
-----
Please enter digits (ex. 1212123): 123
####
###
###
###
###
###
#######
########
###
###
########
#
#
##########
########
###
###
########
###
# ###
########
'''
if __name__ == '__main__':
input_value = input('Please enter digits (ex. 1212123): ')
bs = LargeSizeString(string=input_value)
bs.display()
| true |
bad357e547032486bc7e5b04b7b92351148a2b19 | 21milushcalvin/grades | /Grades.py | 1,649 | 4.25 | 4 | #--By Calvin Milush, Tyler Milush
#--12 December, 2018
#--This program determines a test's letter grade, given a percentage score.
#--Calvin Milush
#-Initializes variables:
score = 0
scoreList = []
counter = 0
total = 0
#--Calvin Milush
#-Looped input for test scores:
while (score != -1):
score = input("Input test score (-1 to exit loop): ")
if (score != -1):
scoreList.append(score)
counter += 1
total += score
else:
break
#--Tyler Milush
#-Assigns a letter grade to each inputted score:
letterList = []
for i in range(counter):
if scoreList[i] >= 90:
letterList.append("A")
elif scoreList[i] >= 80 and scoreList[i] <= 89:
letterList.append("B")
elif scoreList[i] >= 70 and scoreList[i] <= 79:
letterList.append("C")
elif scoreList[i] >= 60 and scoreList[i] <= 69:
letterList.append("D")
elif scoreList[i] < 60:
letterList.append("F")
print
print "List of scores: ", scoreList
print "Grade of each score: ", letterList
print
#--Calvin Milush
#-Calculates and prints average (if greater than 0):
if (counter > 0):
avg = total / float(counter)
print "%0s %0.2f" % ("Average test score: ", avg)
else:
print "Error: Requires at least one test score."
#--Tyler Milush
#-Assigns a letter grade to the average:
avgLetter = ""
if(avg >= 90):
avgLetter = "A"
elif(avg >= 80 and avg <=89):
avgLetter = "B"
elif(avg >= 70 and avg <=79):
avgLetter = "C"
elif(avg >= 60 and avg <=69):
avgLetter = "D"
elif(avg < 60):
avgLetter = "F"
print "Letter grade of average: ", avgLetter
| true |
3f2832d039f29ef99679e8c51d42f5fb08b1dcff | pullannagari/python-training | /ProgramFlow/contrived.py | 425 | 4.21875 | 4 | # con·trived
# /kənˈtrīvd/
# Learn to pronounce
# adjective
# deliberately created rather than arising naturally or spontaneously.
# FOR ELSE, else is activated if all the iterations are complete/there is no break
numbers = [1, 45, 132, 161, 610]
for number in numbers:
if number % 8 == 0:
#reject the list
print("The numbers are unacceptable")
break
else:
print("The numbers are fine") | true |
7f9b228de7c12560ac80445c6b1a4d7543ddc263 | pullannagari/python-training | /Functions_Intro/banner.py | 1,312 | 4.15625 | 4 | # using default parameters,
# the argument becomes
# optional at the caller
def banner_text(text: str = " ", screen_width: int = 60) -> None:
"""
centers the text and prints with padded ** at the start and the end
:param text: string to be centered and printed
:param screen_width: width of the screen on which text should be printed
:raises ValueError: if the supplies string is longer than screen width
"""
if len(text) > screen_width - 4:
raise ValueError("screen {0} is larger than specified width {1}"
.format(text, screen_width))
if text == "*":
print("*" * screen_width)
else:
output_string = "**{0}**".format(text.center(screen_width - 4))
print(output_string)
width = 60
banner_text("*")
banner_text("lorem ipsum lorem ipsum")
banner_text("the quick brown fox jumped over lazy dog")
banner_text(screen_width=60) # key word arguments are used when both
# arguments are optional
banner_text("lorem ipsum lorem ipsum", width)
banner_text("the quick brown fox jumped over the lazy dog", width)
banner_text("*", width)
# result = banner_text("Nothing is returned", width) # returns None by default
# print(result)
# numbers = [ 1, 3, 5, 2, 6]
# print(numbers.sort()) # prints None since sort() returns None
| true |
232c40b3f47c42c8a33fcc5d7e4bde2719969080 | Hemalatah/Python-Basic-Coding | /Practice2.py | 2,684 | 4.125 | 4 | #CRAZY NUMBERS
def crazy_sum(numbers):
i = 0;
sum = 0;
while i < len(numbers):
product = numbers[i] * i;
sum += product;
i += 1;
return sum;
numbers = [2,3,5];
print crazy_sum(numbers);
#FIND THE NUMBER OF PERFECT SQUARES BELOW THIS NUMBER
def square_nums(max):
num = 1;
count = 0;
while num < max:
product = num * num;
if product < max:
count += 1;
num += 1;
return count;
print square_nums(25);
#PRINTS OUT THE ELEMENT IN THE ARRAY WHICH IS EITHER DIVISIBLE BY 3 OR 5
def crazy_nums(max):
i = 1;
list = [];
new_list = [];
while i < max:
list.append(i);
i += 1;
for i in list:
if i % 3 == 0 and i % 5 == 0:
continue;
elif i % 3 == 0 or i % 5 == 0:
new_list.append(i);
else:
continue;
return new_list;
print crazy_nums(3);
#PRINTS OUT THE SUM OF ANY THREE NUMBERS IN THE ARRAY WHICH IS EQUAL TO SEVEN
def lucky_sevens(numbers):
i = 0;
Bool = False;
if len(numbers) <= 1:
print("Length of numbers should be atleast 2");
while i + 2 < len(numbers):
sum = numbers[i] + numbers[i+1] + numbers[i+2];
if sum == 7:
Bool = True;
i += 1;
return Bool;
numbers = [1,2,3,4,5];
print(lucky_sevens(numbers));
numbers = [2,1,5,1,0];
print(lucky_sevens(numbers));
numbers = [0,-2,1,8];
print(lucky_sevens(numbers));
numbers = [7,7,7,7];
print(lucky_sevens(numbers));
numbers = [3,4,3,4];
print(lucky_sevens(numbers));
#FIND THE NUMBER OF ODD ELEMENTS IN THE ARRAY
def oddball_sum(numbers):
i = 0;
sum = 0;
while i < len(numbers):
if (numbers[i]%2) != 0:
sum = sum + numbers[i];
i += 1;
return sum;
numbers = [1,2,3,4,5];
print(oddball_sum(numbers));
numbers = [0,6,4,4];
print(oddball_sum(numbers));
numbers = [1,2,1];
print(oddball_sum(numbers));
#REMOVES VOWEL FROM THE STRING
def disemvowel(string):
vowel = 'aeiou';
i = 0;
while i < len(string):
if string[i] in vowel:
string = string.replace(string[i],"");
else:
i += 1;
return string;
string = "foobar";
print(disemvowel(string));
print(disemvowel("ruby"));
print(disemvowel("aeiou"));
#DASHERIZE THE NUMBER
def odd(intput):
if (intput%2):
return True;
else:
return False;
def dasherize_number(number):
s = str(number);
new_list = [];
i = 0;
while i < len(s):
if odd(int(s[i])):
if i == 0:
new_list.append(s[i]);
new_list.append('-');
elif i == len(s)-1:
new_list.append('-');
new_list.append(s[i]);
elif odd(int(s[i-1])):
new_list.append(s[i]);
new_list.append('-');
else:
new_list.append('-');
new_list.append(s[i]);
new_list.append('-');
else:
new_list.append(s[i]);
i += 1;
new_list = "".join(new_list);
return new_list;
print dasherize_number(3243);
| true |
1ba2daae4ad916e06b92b9277ca113d64bbd3a84 | miss-faerie/Python_the_hard_way | /ex3.py | 507 | 4.25 | 4 | hens = int(25+30/6)
roosters = int(100-25*3%4)
eggs = int(3+2+1-5+4%2-1/4+6)
print()
print("I will now count my chickens:")
print("Hens",hens)
print("Roosters",roosters)
print("Now I will count the eggs:",eggs)
print()
print("Is it true that 3+2 < 5-7 ?",(3+2)<(5-7))
print("What is 3+2 ?",3+2)
print("What is 5-7 ?",5-7)
print("Oh that's why it's False.")
print()
print("How about some more.")
print("Is it greater?",5 > -2)
print("Is it greater or equal?",5 >= -2)
print("Is it less or equal?",5 <= -2) | true |
55e136a4bc7dc3170e38564c14f8ffe09bd16bdd | achkataa/Python-Advanced | /Functions Advanced/5.Odd or Even.py | 352 | 4.125 | 4 | command = input()
numbers = [int(num) for num in input().split()]
def print_results(nums):
print(sum(nums) * len(numbers))
def needed_numbers(nums):
if command == "Odd":
nums = [num for num in nums if num % 2 != 0]
else:
nums = [num for num in nums if num % 2 == 0]
print_results(nums)
needed_numbers((numbers))
| false |
16e176e7b1f43c5c78feea53472ad5cdf2949955 | tsabz/ITS_320 | /Option #2: Repetition Control Structure - Five Floating Point Numbers.py | 1,321 | 4.25 | 4 | values_dict = {
'Module 1': 0,
'Module 2': 0,
'Module 3': 0,
'Module 4': 0,
'Module 5': 0,
}
# first we want to have the student enter grades into set
def Enter_grades():
print('Please enter your grade for Module 1:')
values_dict['Module 1'] = int(float(input()))
print('Please enter your grade for Module 2:')
values_dict['Module 2'] = int(float(input()))
print('Please enter your grade for Module 3:')
values_dict['Module 3'] = int(float(input()))
print('Please enter your grade for Module 4:')
values_dict['Module 4'] = int(float(input()))
print('Please enter your grade for Module 5:')
values_dict['Module 5'] = int(float(input()))
def Average():
avg = 0
for value in values_dict.values():
avg += value
avg = avg / len(values_dict)
print('Your average score is:')
print(float(avg))
def min_max():
# min numbers
minimum = min(values_dict.values())
print('Your lowest score was ' +
min(values_dict) + ':')
print(float(minimum))
# max numbers
maximum = max(values_dict.values())
print('Your highest score was ' + max(values_dict) + ':')
print(float(maximum))
def main():
Enter_grades()
print(values_dict)
Average()
min_max()
if __name__ == "__main__":
main()
| true |
f13d14609b6c98949dc2e70a7de24f4a5e443ca0 | taeheechoi/coding-practice | /FF_mergeTwoSortedLists.py | 1,061 | 4.1875 | 4 | # https://leetcode.com/problems/merge-two-sorted-lists/
# Input: list1 = [1,2,4], list2 = [1,3,4]
# Output: [1,1,2,3,4,4]
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
#create dummy node so we can compare the first node in each list
dummy = ListNode()
#initialise current node pointer
curr = dummy
#while the lists are valid
while list1 and list2:
#if the value is list1 is less than the value in list2
if list1.val < list2.val:
#the next node in the list will be the list1 node
curr.next = list1
list1 = list1.next
else:
#if not then the next node in the list will be the list2 node
curr.next = list2
list2 = list2.next
#increment node
curr = curr.next
#if list1 node is valid but not list2 node add the rest of the nodes from list1
if list1:
curr.next = list1
#if list2 node is valid but not list1 node add the rest of the nodes from list2
elif list2:
curr.next = list2
#return the head of the merged list
return dummy.next | true |
8786abcb461d20e104b4ca579bef7324c1924105 | taeheechoi/coding-practice | /FB/208_062722-implement-trie-prefix-tree.py | 1,053 | 4.21875 | 4 | # https://leetcode.com/problems/implement-trie-prefix-tree/discuss/1804957/Python-3-Easy-solution
class Trie:
def __init__(self):
self.children = {}
self.is_end = False
def insert(self, word):
curr = self
for w in word:
if w not in curr.children:
curr.children[w] = Trie()
print(curr.children)
curr = curr.children[w]
curr.is_end = True
def search(self, word):
curr = self
for w in word:
if w not in curr.children:
return False
curr = curr.children[w]
return curr.is_end
def startsWith(self, prefix):
curr = self
for w in prefix:
if w not in curr.children:
return False
curr = curr.children[w]
return True
obj = Trie()
obj.insert("app")
obj.insert("apple")
# obj.insert("apple")
# print(obj.search("apple"))
# print(obj.search("app"))
# print(obj.startsWith("app"))
| false |
2190f7f62adf79cd2ee82007132c9571e4f0e68b | Codeducate/codeducate.github.io | /students/python-projects-2016/guttikonda_dhanasekar.py | 950 | 4.1875 | 4 | #This program will tell people how much calories they can consume until they have reached their limit.
print("How old are you")
age = int(input())
print("How many calories have you consumed today?")
cc = int(input())
print("Are you a male or female?")
gender = input()
print("Thanks! We are currently calculating your data")
if age <= 3 and gender=="female":
print("You have consumed", 1000-cc)
elif age <= 3 and gender=="male":
print("You have consumed”, 1000-cc)
elif (4 <= age <= 8 and gender==("female"): print("You have consumed", 1200-cc)
elif (4<=age <= 8 and gender=="male"):
print("You have consumed”, 1400-cc)
elif (9 <= age <= 13 and gender=="female"):
print("You have consumed", 1600-cc)
elif (9<=age <= 13 and gender=="male"):
print("You have consumed”, 1800-cc)
elif (14 <= age <= 18 and gender=="female"):
print("You have consumed", 1800-cc)
elif (14<=age <= 18 and gender=="male"):
print("You have consumed”, 2200-cc) | true |
98e78ab456a9b654f37b48fd459c6b24f2560b93 | afmendes/alticelabs | /Programs and Applications/Raspberry Pi 4/Project/classes/Queue.py | 595 | 4.1875 | 4 | # simple queue class with FIFO logic
class Queue(object):
"""FIFO Logic"""
def __init__(self, max_size: int = 1000):
self.__item = []
# adds a new item on the start of the queue
def enqueue(self, add):
self.__item.insert(0, add)
return True
# removes the last items of the queue
def dequeue(self):
if not self.is_empty():
return self.__item.pop()
# checks if the queue is empty and return True if it is, else returns False
def is_empty(self):
if not self.__item:
return True
return False
| true |
4881c26cd1491c9017017296ad830edb28653ae8 | tvumos/dz4 | /borndayforewer.py | 1,200 | 4.46875 | 4 | """
МОДУЛЬ 2
Программа из 2-го дз
Сначала пользователь вводит год рождения Пушкина, когда отвечает верно вводит день рождения
Можно использовать свой вариант программы из предыдущего дз, мой вариант реализован ниже
Задание: переписать код используя как минимум 1 функцию
"""
# Дата рождения А.С Пушкина = 26 мая 1799 г.
pushkin_year = 1799
pushkin_day = 27
def question_answer(question, correct_answer):
user_answer = None
while user_answer != correct_answer:
if user_answer is not None:
print("Не верно")
user_answer = input(question)
while not user_answer.isdigit():
print("Не верно")
user_answer = input(question)
user_answer = int(user_answer)
question_answer('Введите год рождения А.С Пушкина: ', pushkin_year)
question_answer('Введите день рождения А.С Пушкина: ', pushkin_day)
print("Верно")
| false |
eba5b2a0bceea1cc3848e70e0e68fc0f0607a677 | tanishksachdeva/leetcode_prog | /9. Palindrome Number.py | 1,083 | 4.3125 | 4 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
# Follow up: Could you solve it without converting the integer to a string?
# Example 1:
# Input: x = 121
# Output: true
# Example 2:
# Input: x = -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
# Example 3:
# Input: x = 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
# Example 4:
# Input: x = -101
# Output: false
# Constraints:
# -231 <= x <= 231 - 1
class Solution:
def get_rev(self,n):
rev =0
while(n > 0):
r = n %10
rev = (rev *10) + r
n = n //10
return rev
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
rev = self.get_rev(x)
print(rev)
if rev==x:
return True
else:
return False
| true |
3df720d5c88d4d4fca5f8ec14850f9697f737401 | 2000xinxin/pythonProject | /学习代码/flie_baseop.py | 1,281 | 4.1875 | 4 | # 将小说的主要人物记录在文件中
# file1 = open('name.txt', 'w') # 第二个参数 'w' 代表的是写入
# file1.write('诸葛亮')
# file1.close()
# 读取 name.txt 文件的内容
# file2 = open('name.txt')
# print(file2.read())
# file2.close()
#
# file3 = open('name.txt', 'a') # 第二个参数 'a' 代表的是增加
# file3.write('刘备')
# file3.close()
# file4 = open('name.txt')
# print(file4.readline())
# 逐行读取
# file5 = open('name.txt')
# for line in file5.readlines() :
# print(line)
# print('=====') # 为了方便区分,我们在后面多输出一些提示信息
# file6 = open('name.txt')
# print(file6.tell()) # 打印指针所在的位置
# file6.read(1)
# print(file6.tell())
# file6.seek(0) # 返回到文件的开头
# print(file6.tell())
file6 = open('name.txt')
print('当前文件指针的位置 %s' %file6.tell())
print('当前读取到了一个字符,字符的内容是 %s' %file6.read(1))
print('当前文件指针的位置 %s' %file6.tell())
file6.seek(0)
print('我们进行了 seek 操作')
print('当前文件指针的位置 %s' %file6.tell())
print('当前读取到了一个字符,字符的内容是 %s' %file6.read(1))
print('当前文件指针的位置 %s' %file6.tell())
file6.close()
| false |
084a8d9a138e77eba923726e61c139b58170073d | femakin/Age-Finder | /agefinder.py | 1,116 | 4.25 | 4 | #Importing the necessary modules
from datetime import date, datetime
import calendar
#from datetime import datetime
#Getting user input
try:
last_birthday = input('Enter your last birthdate (i.e. 2017,07,01)')
year, month, day = map(int, last_birthday.split(','))
Age_lastbthday = int(input("Age, as at last birthday? "))
#Converting to Date object
date_ = date(year, month, day).weekday()
Year_born = year - Age_lastbthday #Year born from User Input
born_str = str(Year_born) #Birth year to string
conc = (str(Year_born) + str(month) + str(day)) #Concatenation (Year_born, month and day) from date object
born_date = datetime.strptime(conc, '%Y%m%d') #To get the necessary date format
week = datetime.strptime(conc, '%Y%m%d').weekday() #To get the actual birth day of the week
print(f"Thank you for coming around. You were born on { born_date} which happens to be on {(calendar.day_name[week]) }")
#print( (calendar.day_name[week]) )
except:
ValueError
print("Wrong Input! Please make sure your input is in this format: 2017,07,01 ")
quit()
| true |
57249ecd6489b40f0ca4d3ea7dd57661b436c106 | tjastill03/PythonExamples | /Iteration.py | 343 | 4.15625 | 4 | # Taylor Astill
# What is happening is a lsit has been craeted and the list is being printed.
# Then it is sayingfor each of the listed numbers
# list of numbers
numberlist = [1,2,3,4,5,6,7,8,9,10]
print(numberlist)
# iterate over the list
for entry in numberlist:
# Selection over the iteration
if (entry % 2) == 0:
print(entry) | true |
fee46693ff557202fba24ba5a16126341624fdd6 | lepaclab/Python_Fundamentals | /Medical_Insurance.py | 2,599 | 4.6875 | 5 | # Python Syntax: Medical Insurance Project
# Suppose you are a medical professional curious
#about how certain factors contribute to medical
#insurance costs. Using a formula that estimates
#a person’s yearly insurance costs, you will investigate
#how different factors such as age, sex, BMI, etc. affect the prediction.
# Our first step is to create the variables for each factor we will consider when estimating medical insurance costs.
# These are the variables we will need to create:
# age: age of the individual in years
# sex: 0 for female, 1 for male*
# bmi: individual’s body mass index
# num_of_children: number of children the individual has
# smoker: 0 for a non-smoker, 1 for a smoker
# At the top of script.py, create the following variables for a 28-year-old, nonsmoking woman who has three children and a BMI of 26.2
# create the initial variables below
age = 28
sex = 0
bmi = 26.2
num_of_children = 3
smoker = 0
# Add insurance estimate formula below
insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
print("This person's insurance cost is", insurance_cost, "dollars.")
# Age Factor
age += 4
# BMI Factor
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("The change in cost of insurance after increasing the age by 4 years is " + str(change_in_insurance_cost) + " dollars.")
age = 28
bmi += 3.1
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("The change in estimated insurance cost after increasing BMI by 3.1 is " + str(change_in_insurance_cost) + " dollars.")
# Male vs. Female Factor
bmi = 26.2
sex = 1
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("The change in estimated cost for being male instead of female is " + str(change_in_insurance_cost) + " dollars")
# Notice that this time you got a negative value for change_in_insurance_cost. Let’s think about what this means. We changed the sex variable from 0 (female) to 1 (male) and it decreased the estimated insurance costs.
# This means that men tend to have lower medical costs on average than women. Reflect on the other findings you have dug up from this investigation so far.
# Extra Practice
| true |
49f8b9cfb5f19a643a0bacfe6a775c7d33d1e95d | denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions | /Recursion/NthFibonacci.py | 713 | 4.34375 | 4 | # Nth Fibonacci
# Difficulty: Easy
# Instruction:
#
# The Fibonacci sequence is defined as follows: the first number of the sequence
# is 0 , the second number is 1 , and the nth number is the sum of the (n - 1)th
# and (n - 2)th numbers. Write a function that takes in an integer "n"
# and returns the nth Fibonacci number.
# Solution 1: Recurision
def getNthFib(n):
# Write your code here.
if n == 1:
return 0
if n == 2:
return 1
return getNthFib(n-1) + getNthFib(n-2)
# Solution 2: Memoize
def getNthFib(n):
# Write your code here.
d = {
1 : 0,
2 : 1
}
if n in d:
return d[n]
else:
for i in range(3, n+1):
d[i] = d[i - 1] + d[i - 2]
return d[n]
| true |
adffbd365423fb9421921d4ca7c0f5765fe0ac60 | denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions | /Arrays/ThreeNumSum.py | 1,745 | 4.34375 | 4 | # ThreeNumSum
# Difficulty: Easy
# Instruction:
# Write a function that takes in a non-empty array of distinct integers and an
# integer representing a target sum. The function should find all triplets in
# the array that sum up to the target sum and return a two-dimensional array of
# all these triplets. The numbers in each triplet should be ordered in ascending
# order, and the triplets themselves should be ordered in ascending order with
# respect to the numbers they hold.
# If no three numbers sum up to the target sum, the function should return an
# empty array.
# Solution 1:
def threeNumberSum(array, targetSum):
# Write your code here.
array.sort()
ans = []
for i in range(len(array)):
left = i + 1
right = len(array) - 1
while left < right:
curSum = array[i] + array[left] + array[right]
if curSum == targetSum:
ans.append([array[i], array[left], array[right]])
left += 1
right -= 1
elif curSum < targetSum:
left += 1
elif curSum > targetSum:
right -= 1
return ans
# Solution 2:
ans = []
d ={}
for i in range(len(array)):
for j in range(len(array)):
if i == j:
continue
num = targetSum - (array[i] + array[j])
if num in d:
d[num].append([array[i], array[j]])
else:
d[num] = [[array[i], array[j]]]
for i in range(len(array)):
if array[i] in d:
for j in range(len(d[array[i]])):
if array[i] in d[array[i]][j]:
continue
possible_ans = d[array[i]][j][0] + d[array[i]][j][1] + array[i]
if possible_ans == targetSum:
d[array[i]][j].append(array[i])
d[array[i]][j].sort()
if d[array[i]][j] not in ans:
ans.append(d[array[i]][j])
ans.sort()
return ans
| true |
e7499f4caab0fb651b8d9a3fc5a7c374d184d28f | akhileshsantoshwar/Python-Program | /Programs/P07_PrimeNumber.py | 660 | 4.40625 | 4 | #Author: AKHILESH
#This program checks whether the entered number is prime or not
def checkPrime(number):
'''This function checks for prime number'''
isPrime = False
if number == 2:
print(number, 'is a Prime Number')
if number > 1:
for i in range(2, number):
if number % i == 0:
print(number, 'is not a Prime Number')
isPrime = False
break
else:
isPrime = True
if isPrime:
print(number, 'is a Prime Number')
if __name__ == '__main__':
userInput = int(input('Enter a number to check: '))
checkPrime(userInput)
| true |
4fe9d7b1d738012d552b79fb4dc92a3c65fa7e53 | akhileshsantoshwar/Python-Program | /Programs/P08_Fibonacci.py | 804 | 4.21875 | 4 | #Author: AKHILESH
#This program calculates the fibonacci series till the n-th term
def fibonacci(number):
'''This function calculates the fibonacci series till the n-th term'''
if number <= 1:
return number
else:
return (fibonacci(number - 1) + fibonacci(number - 2))
def fibonacci_without_recursion(number):
if number == 0: return 0
fibonacci0, fibonacci1 = 0, 1
for i in range(2, number + 1):
fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1
return fibonacci1
if __name__ == '__main__':
userInput = int(input('Enter the number upto which you wish to calculate fibonnaci series: '))
for i in range(userInput + 1):
print(fibonacci(i),end=' ')
print("\nUsing LOOP:")
print(fibonacci_without_recursion(userInput))
| true |
3060667c2327aa358575d9e096d9bdc353ebedaa | akhileshsantoshwar/Python-Program | /Programs/P11_BinaryToDecimal.py | 604 | 4.5625 | 5 | #Author: AKHILESH
#This program converts the given binary number to its decimal equivalent
def binaryToDecimal(binary):
'''This function calculates the decimal equivalent to given binary number'''
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
print('Decimal equivalent of {} is {}'.format(binary1, decimal))
if __name__ == '__main__':
userInput = int(input('Enter the binary number to check its decimal equivalent: '))
binaryToDecimal(userInput)
| true |
c3e19b89c753c95505dc168514dd760f486dd4b9 | akhileshsantoshwar/Python-Program | /OOP/P03_InstanceAttributes.py | 619 | 4.21875 | 4 | #Author: AKHILESH
#In this example we will be seeing how instance Attributes are used
#Instance attributes are accessed by: object.attribute
#Attributes are looked First in the instance and THEN in the class
import random
class Vehicle():
#Class Methods/ Attributes
def type(self):
#NOTE: This is not a class attribute as the variable is binded to self. Hence it becomes
#instance attribute
self.randomValue = random.randint(1,10) #Setting the instance attribute
car = Vehicle()
car.type() #Calling the class Method
print(car.randomValue) #Calling the instance attribute
| true |
74d0b16405a97e6b5d2140634f2295d466b50e64 | akhileshsantoshwar/Python-Program | /Programs/P54_PythonCSV.py | 1,206 | 4.3125 | 4 | # Author: AKHILESH
# In this example we will see how to use CSV files with Python
# csv.QUOTE_ALL = Instructs writer objects to quote all fields.
# csv.QUOTE_MINIMAL = Instructs writer objects to only quote those fields which contain special characters such
# as delimiter, quotechar or any of the characters in lineterminator.
# csv.QUOTE_NONNUMERIC = Instructs writer objects to quote all non-numeric fields.
# Instructs the reader to convert all non-quoted fields to type float.
# csv.QUOTE_NONE = Instructs writer objects to never quote fields.
import csv
def csvRead(filePath):
with open(filePath) as fd:
reader = csv.reader(fd, delimiter = ',')
for row in reader:
print(row[0] + ' ' + row[1])
def csvWrite(filePath, data):
with open(filePath, 'a') as fd:
writer = csv.writer(fd, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(data)
if __name__ == '__main__':
# data = ['Firstname', 'Lastname']
# csvWrite('example.csv', data)
userInput = input('What is your Fullname? ')
userInput = userInput.split(' ')
csvWrite('example.csv', userInput)
csvRead('example.csv')
| true |
0488727a912f98123c6e0fdd47ccde36df895fbd | akhileshsantoshwar/Python-Program | /Programs/P63_Graph.py | 2,160 | 4.59375 | 5 | # Author: AKHILESH
# In this example, we will see how to implement graphs in Python
class Vertex(object):
''' This class helps to create a Vertex for our graph '''
def __init__(self, key):
self.key = key
self.edges = {}
def addNeighbour(self, neighbour, weight = 0):
self.edges[neighbour] = weight
def __str__(self):
return str(self.key) + 'connected to: ' + str([x.key for x in self.edges])
def getEdges(self):
return self.edges.keys()
def getKey(self):
return self.key
def getWeight(self, neighbour):
try:
return self.edges[neighbour]
except:
return None
class Graph(object):
''' This class helps to create Graph with the help of created vertexes '''
def __init__(self):
self.vertexList = {}
self.count = 0
def addVertex(self, key):
self.count += 1
newVertex = Vertex(key)
self.vertexList[key] = newVertex
return newVertex
def getVertex(self, vertex):
if vertex in self.vertexList:
return self.vertexList[vertex]
else:
return None
def addEdge(self, fromEdge, toEdge, cost = 0):
if fromEdge not in self.vertexList:
newVertex = self.addVertex(fromEdge)
if toEdge not in self.vertexList:
newVertex = self.addVertex(toEdge)
self.vertexList[fromEdge].addNeighbour(self.vertexList[toEdge], cost)
def getVertices(self):
return self.vertexList.keys()
def __iter__(self):
return iter(self.vertexList.values())
if __name__ == '__main__':
graph = Graph()
graph.addVertex('A')
graph.addVertex('B')
graph.addVertex('C')
graph.addVertex('D')
graph.addEdge('A', 'B', 5)
graph.addEdge('A', 'C', 6)
graph.addEdge('A', 'D', 2)
graph.addEdge('C', 'D', 3)
for vertex in graph:
for vertexes in vertex.getEdges():
print('({}, {}) => {}'.format(vertex.getKey(), vertexes.getKey(), vertex.getWeight(vertexes)))
# OUTPUT:
# (C, D) => 3
# (A, C) => 6
# (A, D) => 2
# (A, B) => 5
| true |
8271310a83d59aa0d0d0c392a16a19ef538c749d | akhileshsantoshwar/Python-Program | /Numpy/P06_NumpyStringFunctions.py | 1,723 | 4.28125 | 4 | # Author: AKHILESH
import numpy as np
abc = ['abc']
xyz = ['xyz']
# string concatenation
print(np.char.add(abc, xyz)) # ['abcxyz']
print(np.char.add(abc, 'pqr')) # ['abcpqr']
# string multiplication
print(np.char.multiply(abc, 3)) # ['abcabcabc']
# numpy.char.center: This function returns an array of the required width so that the input string is
# centered and padded on the left and right with fillchar.
print(np.char.center(abc, 20, fillchar = '*')) # ['********abc*********']
# numpy.char.capitalize(): This function returns the copy of the string with the first letter capitalized.
print(np.char.capitalize('hello world')) # Hello world
# numpy.char.title(): This function returns a title cased version of the input string with the first letter
# of each word capitalized.
print(np.char.title('hello how are you?')) # Hello How Are You?
# numpy.char.lower(): This function returns an array with elements converted to lowercase. It calls
# str.lower for each element.
print(np.char.lower(['HELLO','WORLD'])) # ['hello' 'world']
# numpy.char.upper(): This function calls str.upper function on each element in an array to return
# the uppercase array elements.
print(np.char.upper('hello')) # HELLO
# numpy.char.split(): This function returns a list of words in the input string. By default, a whitespace
# is used as a separator
print(np.char.split('Abhi Patil')) # ['Abhi', 'Patil']
print(np.char.split('2017-02-11', sep='-')) # ['2017', '02', '11']
# numpy.char.join(): This method returns a string in which the individual characters are joined by
# separator character specified.
print(np.char.join(':','dmy')) # d:m:y
| true |
384c45c69dc7f7896f84c42fdfa9e7b9a4a1d394 | tobyatgithub/data_structure_and_algorithms | /challenges/tree_intersection/tree_intersection.py | 1,392 | 4.3125 | 4 | """
In this file, we write a function called tree_intersection that
takes two binary tree parameters. Without utilizing any of the
built-in library methods available to your language, return a
set of values found in both trees.
"""
def tree_intersection(tree1, tree2):
"""
This function takes in two binary trees as input,
read the first tree and store everything into a
dictionary.
Traverse the second tree and compare. (notice that
we don't store data of second tree.)
"""
store = {}
def preOrder1(tree, root, storage={}):
"""
Traverse tree 1
"""
if root:
value = root.val
storage.setdefault(value, 0)
storage[value] += 1
preOrder1(tree, root.left, storage=storage)
preOrder1(tree, root.right, storage=storage)
preOrder1(tree1, tree1.root, store)
duplicate = []
def preOrder2(tree, root, storage):
"""
Traverse tree 2 and compare
"""
if root:
value = root.val
if value in storage.keys():
duplicate.append(value)
else:
storage.setdefault(value, 0)
storage[value] += 1
preOrder2(tree, root.left, storage)
preOrder2(tree, root.right, storage)
preOrder2(tree2, tree2.root, store)
return set(duplicate)
| true |
212ea767940360110c036e885c544609782f9a82 | tobyatgithub/data_structure_and_algorithms | /data_structures/binary_tree/binary_tree.py | 1,454 | 4.375 | 4 | """
In this file, we make a simple implementation of binary
tree.
"""
import collections
class TreeNode:
def __init___(self, value=0):
self.value = value
self.right = None
self.left = None
def __str__(self):
out = f'This is a tree node with value = { self.val } and left = { self.left } and right = { self.right }'
return out
def __repr__(self):
out = f'This is a tree node with value = { self.val } and left = { self.left }'
f'and right = { self.right }'
return out
class binary_tree:
def __init__(self, iterable=[]):
self.root = None
self.index = 0
if iterable:
if isinstance(iterable, collections.Iterable):
for i in iterable:
self.insert(i)
else:
raise TypeError('Binary_tree class takes None or Iterable \
input, got {}'.format(type(iterable)))
def __str__(self):
out = f'This is a binay tree with root = { self.root.val }'
return out
def __repr__(self):
out = f'This is a binay tree with root = { self.root.val }'
return out
def insert(self, value=0):
pass
# I just notice that...most implementation online
# about binary tree is actually BST...
# which is easier to implement insert
# otherwise...shall we keep an index to keep track of
# insertion?
| true |
8e05603d65047bb6f747be134a6b9b6554f5d9cc | ganguli-lab/nems | /nems/nonlinearities.py | 757 | 4.21875 | 4 | """
Nonlinearities and their derivatives
Each function returns the value and derivative of a nonlinearity. Given :math:`y = f(x)`, the function returns
:math:`y` and :math:`dy/dx`
"""
import numpy as np
def exp(x):
"""Exponential function"""
# compute the exponential
y = np.exp(x)
# compute the first and second derivatives
dydx = y
dy2dx2 = y
return y, dydx, dy2dx2
def softrect(x):
""" Soft rectifying function
.. math::
y = \log(1+e^x)
"""
# compute the soft rectifying nonlinearity
x_exp = np.exp(x)
y = np.log1p(x_exp)
# compute the derivative
dydx = x_exp / (1 + x_exp)
# compute the second derivative
dy2dx2 = x_exp / (1 + x_exp)**2
return y, dydx, dy2dx2
| true |
f11cabe118d21fc4390c6dc84a85581f374a4e8f | liming870906/Python2_7Demo | /demos/D004_MaxNumber.py | 323 | 4.125 | 4 |
number1 = int(input("number1:"))
number2 = int(input("number2:"))
number3 = int(input("number3:"))
if number1 >= number2:
if number1 >= number3:
print("Max:",number1)
else:
print("Max:",number3)
else:
if number2 >= number3:
print("Max:",number2)
else:
print("Max:",number3) | false |
4851bf916952b52b1b52eb1d010878e33bba3855 | tusvhar01/practice-set | /Practice set 42.py | 489 | 4.25 | 4 | my_tuple = tuple((1, 2, "string"))
print(my_tuple)
my_list = [2, 4, 6]
print(my_list) # outputs: [2, 4, 6]
print(type(my_list)) # outputs: <class 'list'>
tup = tuple(my_list)
print(tup) # outputs: (2, 4, 6)
print(type(tup)) # outputs: <class 'tuple'>
#You can also create a tuple using a Python built-in function called tuple().
# This is particularly useful when you want to convert a certain iterable (e.g., a list, range, string, etc.) to a tuple: | true |
37c28ad515026a3db91878d907f7d31e14f7e9a7 | tusvhar01/practice-set | /Practice set 73.py | 472 | 4.125 | 4 | a=input("Enter first text: ")
b=input("Enter second text: ")
a=a.upper()
b=b.upper()
a=a.replace(' ','')
b=b.replace(' ','')
if sorted(a)==sorted(b):
print("It is Anagram") # anagram
else:
print("Not Anagram")
#An anagram is a new word formed by rearranging the letters of a word, using all the original
# letters exactly once. For example, the phrases
# "rail safety" and "fairy tales" are anagrams, while "I am" and "You are" are not.
| true |
bd50429e48eae21d7a37647c65ae61866c1e97cb | dviar2718/code | /python3/types.py | 1,259 | 4.1875 | 4 | """
Python3 Object Types
Everything in Python is an Object.
Python Programs can be decomposed into modules, statements, expressions, and
objects.
1. Programs are composed of modules.
2. Modules contain statements.
3. Statements contain expressions.
4. Expressions create and process objects
Object Type Example
----------- ---------------------------------------------------
Numbers 1234, 3.14159, 3 + 4j, Ob111, Decimal(), Fraction()
Strings 'spam', "Bob's", b'a\x01c', u'sp\xc4m'
Lists [1, [2, 'three'], 4.5], list(range(10))
Dictionaries {'food':'spam', 'taste':'yum'}, dict(hours=10)
Tuples (1,'spam', 4, 'U'), tuple('spam'), namedtuple
Files open('eggs.txt'), open(r'C:\ham.bin', 'wb')
Sets set('abc'), {'a', 'b', 'c'}
Other core types Booleans, types, None
Program unit types Functions, modules, classes
Implementation related types Compiled code, stack tracebacks
Once you create an object, you bind its operation set for all time.
This means that Python is dynamically typed.
It is also strongly typed (you can only do to an object what it allows)
Immutable Objects
------------------------
Numbers, Strings, Tuples
Mutable Objects
------------------------
Lists, Dictionaries, Sets
"""
| true |
1a7b97bce6b4c638d505e1089594f54914485ec0 | shaner13/OOP | /Week 2/decimal_to_binary.py | 598 | 4.15625 | 4 | #intiialising variables
decimal_num = 0
correct = 0
i = 0
binary = ''
while(correct==0):
decimal_num = int(input("Enter a number to be converted to binary.\n"))
if(decimal_num>=0):
correct = correct + 1
#end if
else:
print("Enter a positive integer please.")
#end else
#end while
while(decimal_num>0):
if(decimal_num % 2 == 0):
binary = binary + '0'
#end if
else:
binary = binary + '1'
#end else
decimal_num = decimal_num // 2
#end while
print("Your number in binary is:\n")
print(binary[::-1])
#end for
| true |
294115d83f56263f56ff23790c35646fa69f8342 | techreign/PythonScripts | /batch_rename.py | 905 | 4.15625 | 4 | # This will batch rename a group of files in a given directory to the name you want to rename it to (numbers will be added)
import os
import argparse
def rename(work_dir, name):
os.chdir(work_dir)
num = 1
for file_name in os.listdir(work_dir):
file_parts = (os.path.splitext(file_name))
os.rename(file_name, name + str(num) + file_parts[1])
num += 1
def get_parser():
parser = argparse.ArgumentParser(description="Batch renaming of files in a folder")
parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, help='the directory where you wish to rename the files')
parser.add_argument('name', metavar='NAME', type=str, nargs=1, help='the new name of the files')
return parser
def main():
parser = get_parser()
args = vars(parser.parse_args())
work_dir = args['work_dir'][0]
name = args['name'][0]
rename(work_dir, name)
if __name__ == "__main__":
main()
| true |
f08a7e8583fe03de82c43fc4a032837f5ac43b06 | bartoszmaleta/python-microsoft-devs-yt-course | /25th video Collections.py | 1,278 | 4.125 | 4 | from array import array # used later
names = ['Bartosz', 'Magda']
print(names)
scores = []
scores.append(98) # Add new item to the end
scores.append(85)
print(scores)
print(scores[1]) # collections are zero-indexed
points = array('d') # d stands for digits
points.append(44)
points.append(12)
print(points)
print(points[1])
# Arrays:
# - designed for simple types such as numbers
# - must all be the same type
# Lists:
# - store anything
# - store any type
last_names = ['Maleta', 'Huget']
print(len(last_names)) # get the number of items in last_names
last_names.insert(0, 'Krawiec') # Insert before index
print(last_names)
last_names.sort()
print(last_names)
# _________________________
# Retrieving ranges
second_names = ['Messi', 'Ronaldo', 'Rooney']
footballers = second_names[0:2] # will get the first two items!
# first number is starting index, second number is number of
# items to retrieve
print(second_names)
print(footballers)
# ___________________________
# Dictionaries
person = {'first': 'Jakub'}
person['last'] = 'Maleta'
print(person)
print(person['first'])
# Dictionaries:
# - key/value pairs
# - storage order not guaranteed
# Lists
# - zero-based index
# - storage order guaranteed | true |
9eb9c7ecf681c8ccc2e9d89a0c8324f94560a1f3 | bartoszmaleta/python-microsoft-devs-yt-course | /31st - 32nd video Parameterized functions.py | 878 | 4.28125 | 4 | # same as before:
def get_initial2(name):
initial = name[0:1].upper()
return initial
first_name3 = input("Enter your firist name: ")
last_name3 = input("Enter your last name: ")
print('Your initials are: ' + get_initial2(first_name3) + get_initial2(last_name3))
# ___________________
def get_iniial(name, force_uppercase=True):
# force_uppercase and False added, to have a
# option to choose whether you want upperacse or not
if force_uppercase:
initial = name[0:1].upper()
else:
initial = name[0:1]
return initial
first_name = input('Enter your fist name: ')
first_name_initial = get_iniial(first_name, False)
# or
# first_name_initial = get_iniial(force_uppercase=False, \
# name-first_name)
# dont have to be in order, if there is "="!!!!!
print('Your inital is: ' + first_name_initial) | true |
2fb0f374d4b6e0b4e08b9dd6cdd324c903537832 | MMVonnSeek/Hacktoberfest-2021 | /Python-Programs/Reverse_Doubly_Linked_List_Using_Stack.py | 1,291 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.prev = None
self.data = data
self.next = None
class Doubly_Linked_List:
def __init__(self):
self.head = None
def Add_at_front(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
new_node.prev = None
if self.head is not None:
self.head.prev = new_node
self.head = new_node
def Reverse_Linked_List(self):
temp = self.head
stack = []
while temp is not None:
stack.append(temp.data)
temp = temp.next
temp = self.head
while temp is not None:
temp.data = stack.pop()
temp = temp.next
def Display(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
if __name__ == "__main__":
L_list = Doubly_Linked_List()
L_list.Add_at_front(5)
L_list.Add_at_front(7)
L_list.Add_at_front(9)
L_list.Add_at_front(8)
L_list.Add_at_front(1)
L_list.Add_at_front(2)
print("\nOriginal Linked List: ")
L_list.Display()
print("\nReverse Linked List: ")
L_list.Reverse_Linked_List()
L_list.Display()
| false |
6544630135a7287c24d1ee167285dc00202cb9aa | MMVonnSeek/Hacktoberfest-2021 | /Python-Programs/avg-parse.py | 1,168 | 4.15625 | 4 | # Total, Average and Count Computation from numbers in a text file with a mix of words and numbers
fname = input("Enter file name: ")
# Ensure your file is in the same folder as this script
# Test file used here is mbox.txt
fhandle = open(fname)
# Seeking number after this word x
x = "X-DSPAM-Confidence:"
y = len(x)
# This shows that the total number of characters is 19
print(y)
# This would show that character 19 is ':' where you can slice to get the numbers after that
print(x[18:])
# Create count to count number of numbers
count = 0
# Create total to sum all the numbers
total = 0
for line in fhandle:
if line.startswith(x):
# Slice the number from the sentence
line_number = line[19:]
line_number = float(line_number)
# print(line_number)
# This shows that we have successfully extracted the floating numbers
# Loop, iterates through all numbers to count number of numbers
count += 1
# Loop, iterates through all numbers to count sum of numbers
total += line_number
print("Count of numbers", count)
print("Sum of numbers", total)
print("Average of numbers", total / count)
| true |
6934e148c95348cd43a07ddb86fadc5723a0e003 | MMVonnSeek/Hacktoberfest-2021 | /Python-Programs/number_decorator.py | 543 | 4.34375 | 4 | # to decorate country code according to user defined countrycode
# the best practical way to learn python decorator
country_code = {"nepal": 977, "india": 91, "us": 1}
def formatted_mob(original_func):
def wrapper(country, num):
country = country.lower()
if country in country_code:
return f"+{country_code[country]}-{original_func(country,num)}"
else:
return num
return wrapper
@formatted_mob
def num(country, num):
return num
number = num("nepal", 9844718578)
print(number)
| true |
dc882ac280f0b5c40cbc1d69ee9db9529e1ad001 | Raviteja02/CorePython | /venv/Parameters.py | 2,308 | 4.28125 | 4 |
#NonDefault Parameters: we will pass values to the non default parameters at the time of calling the function.
def add(a,b):
c = a+b
print(c)
add(100,200)
add(200,300)
print(add) #function address storing in a variable with the name of the function.
sum=add #we can assign the function variable to any user defined variable.
sum(10,20) #and we can access the function with that variable name.
#Default Parameters: we will pass values to the default parameters while creating the function.
def sub(d=20,e=30):
f=e-d
print(f)
sub()
sub(30)
sub(10,40) #if we pass values to default parameters it will override the existing values and give results.
def mult(g,h=10): #one NonDefault and Default Parameter.
i=g*h
print(i)
mult(20)
#def div(j=10,k): #error Default parameter folows Nondefault parameter.
# l=j/k #it wont work.,we can't define a Nondefault parameter after defining Default parameter.
#Orbitary Parameters: the parameters which are preceeded by the (*) are konwn as orbitary Parameters.
def ravi(*a): #Single Star Orbitary Parameter it returns tuple as a result.
print(a)
print(type(a))
ravi()
ravi(10,20,30)
def teja(j,*k):
print(j)
print(type(j))
print(k)
print(type(k))
teja(10,20,30,40)
#def sai(*l,m): Nondefault parameter follwed by sigle star 0rbitary parameter will wont work
# print(l)
# print(type(l))
# print(m)
# print(type(m))
#sai(5,60,70,80)
def satya(*l,m): #Nondefault parameter follwed by sigle star 0rbitary parameter will wont work
print(l)
print(type(l))
print(m)
print(type(m))
satya(5,60,70,80,m=90)
def sai(*l,m=20):
print(l)
print(type(l))
print(m)
print(type(m))
sai(8,40,70,60)
def myfunc(**a): #Multi Star Orbitary Parameter and it will return dictionary as a result
print(a)
print(type(a))
myfunc(x=10,y=20,z=30)
#Arguments
#NonKeyWord Arguments also known as positional arguments.
def nonkeyword(name,msg):
print("Hello",name,msg)
nonkeyword("raviteja","good Morning")
nonkeyword("good Morning","Raviteja")
#Keyword Arguments also known as NOnPositional Arguments.
def keyword(name,msg):
print("Hello",name,msg)
keyword(name="raviteja",msg="good Morning")
keyword(msg="good Morning",name="raviteja")
| true |
0f32a56ec557f7a68cbcf591e5d43b4ba8bd84a8 | abiramikawaii/Python | /sum-of-multiples.py | 265 | 4.21875 | 4 | def sum_of_multiples(a,b, n):
ans=0
for i in range (1,n):
if(i%a==0 or i%b==0):
ans=ans+i
print("Sum of multiples of ", a,"and",b,
"for all the natural numbers below ", n, " is ", int(ans))
# Driver Code
sum_of_multiples(3,5, 20)
| false |
3b1bbf74275f81501c8aa183e1ea7d941f075f56 | Tadiuz/PythonBasics | /Functions.py | 2,366 | 4.125 | 4 | # Add 1 to a and store it in B
def add1(a):
"""
This function takes as parameter a number and add one
"""
B = a+1
print(a," if you add one will be: ",B)
add1(5)
print(help(add1))
print("*"*100)
# Lets declare a function that multiplies two numbers
def mult(a,b):
C = a*b
return C
print("This wont be printed")
Result = mult(12,2)
print(Result)
print("*"*100)
# Lets sen string as a paramenter to our multiplication function
Result = mult(5, " Hello World ")
print(Result)
print("*"*100)
# Function definition
def square(a):
"""
Square the input and add 1
"""
b = 1
c = a*a+b
print(a, " If you square +1 ", c)
z = square(2)
print("*"*100)
# Firs block
A1 = 4
B1 = 5
C1 = A1*B1+2*A1*B1-1
if (C1 < 0):
C1 = 0
else:
C1 = 5
print(C1)
print("*"*100)
# Firs block
A1 = 0
B1 = 0
C1 = A1*B1+2*A1*B1-1
if (C1 < 0):
C1 = 0
else:
C1 = 5
print(C1)
print("*"*100)
# Make a function for the calculation above
def equation(A1,B1):
C1 = A1 * B1 + 2 * A1 * B1 - 1
if (C1 < 0):
C1 = 0
else:
C1 = 5
return C1
C2 = equation(4,5)
C3 = equation(0,0)
print(C2)
print(C3)
print("*"*100)
# Example for setting a parameter with default value
def isGoodRaiting(rating = 4):
if(rating < 7):
print("This album sucks it's raiting is: ", rating)
else:
print("This album is good it's raiting is: ", rating)
isGoodRaiting(1)
isGoodRaiting(10)
isGoodRaiting()
print("*"*100)
# Lets create a function with packed arguments
def printAll(*args):
print("Num of arguments: ", len(args))
for argument in args:
print(argument)
printAll("Red", "Yellow", "Blue", "Orange")
print("*"*100)
printAll("Red", "Yellow")
print("*"*100)
# Kwargs parameter
def printDictionary(**kwargs):
for key in kwargs:
print(key + ": " + kwargs[key])
printDictionary(Country = 'Canada', Providence = 'Ontario', City = 'Toronto')
print("*"*100)
# Funtion
def addItems(list):
list.append("Three")
list.append("Four")
My_list = ["One", "Two"]
print(My_list)
addItems(My_list)
print(My_list)
print("*"*100)
#Example of a global variable
Artist = "Michael Jackson"
def printer1(artist):
global internal_var
internal_var = "Elvis"
print(artist," is an artist")
printer1(Artist)
printer1(internal_var)
| true |
b2c4bb3420c54e65d601c16f3bc3e130372ae0de | nfarnan/cs001X_examples | /functions/TH/04_main.py | 655 | 4.15625 | 4 | def main():
# get weight from the user
weight = float(input("How heavy is the package to ship (lbs)? "))
if weight <= 0:
print("Invalid weight (you jerk)")
total = None
elif weight <= 2:
# flat rate of $5
total = 5
# between 2 and 6 lbs:
elif weight <= 6:
# $5 + $1.50 per lb over 2
total = 5 + 1.5 * (weight - 2)
# between 6 and 10 lbs:
elif weight <= 10:
# $11 + $1.25 per lb over 6
total = 11 + 1.25 * (weight - 6)
# over 10 lbs:
else:
# $16 + $1 per lb over 10
total = 16 + (weight - 10)
if total != None:
# output total cost to user:
print("It will cost $", format(total, ".2f"), " to ship", sep="")
main()
| true |
b5dd5d77115b2c9206c4ce6c22985e362f13c15e | nfarnan/cs001X_examples | /exceptions/MW/03_input_valid.py | 529 | 4.21875 | 4 | def get_non_negative():
valid = False
while not valid:
try:
num = int(input("Enter a non-negative int: "))
except:
print("Invalid! Not an integer.")
else:
if num < 0:
print("Invalid! Was negative.")
else:
valid = True
return num
def get_non_negative2():
while True:
try:
num = int(input("Enter a non-negative int: "))
except:
print("Invalid! Not an integer.")
else:
if num < 0:
print("Invalid! Was negative.")
else:
return num
an_int = get_non_negative()
print(an_int)
| true |
c1d825716a2c9b68e5e247420ebd50cef03fef07 | AnastasisKapetanis/mypython | /askhseisPython/askhsh9.py | 260 | 4.1875 | 4 | num = input("Give a number: ")
num = int(num)
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
while(len(str(int(num)))>1):
num = num*3 + 1
num =sum_digits(num)
print("The number is: " + str(num))
| false |
d0410d0788621701d56ad8b56e6f49cb048c227b | mhashilkar/Python- | /2.1if_statment.py | 238 | 4.25 | 4 | """
THIS IS A BASIC IF STATMENT IN PYTHON
tuna = "fish"
if tuna == "fish":
print('this is a fish alright', tuna)
"""
tuna = "fish"
if tuna == "fish": # IF THE STATMENT IS TRUE THE IT WILL PRINT THE STATMENT
print('allright')
| false |
b862f9fd6aad966de8bd05c2bfcb9f9f12ba61f5 | mhashilkar/Python- | /2.9.7_Variable-length_arguments.py | 590 | 4.5 | 4 | # When you need to give more number of arguments to the function
# " * "used this symbol tho the argument that means it will take multiple value
# it will be a tuple and to print that args you have to used the for loop
def printinfo(args1, *vartuple):
print("Output is: ")
print(args1)
for var in vartuple:
print(var)
printinfo(10,20)
printinfo(10,20,30,40)
def test_var_args(f_args, *argvs):
print("First normal args:", f_args)
for var in argvs:
print("another arg through *argvs: ",var)
test_var_args('yahoo','Google','Python','PHP','Angular.js')
| true |
d93ead75f6ee6fa3198d0a243b063a4a5795544b | OscarMCV/Monomials-Python | /main.py | 2,954 | 4.125 | 4 | """Main program."""
from monomial import Monomial
def test_monomial_string_representation():
"""Prints monomials to test __str__ method."""
print(Monomial(0, 0))
print(Monomial(0, 1))
print(Monomial(0, 5))
print(Monomial(1, 0))
print(Monomial(1, 1))
print(Monomial(1, 5))
print(Monomial(7.5, 0))
print(Monomial(7.5, 1))
print(Monomial(7.5, 5))
print(Monomial(-0, 0))
print(Monomial(-0, 1))
print(Monomial(-0, 5))
print(Monomial(-1, 0))
print(Monomial(-1, 1))
print(Monomial(-1, 5))
print(Monomial(-7.5, 0))
print(Monomial(-7.5, 1))
print(Monomial(-7.5, 5))
print(Monomial(91, 0))
print(Monomial(91, 1))
print(Monomial(91, 5))
test_monomial_string_representation()
print('This program allows to perform basic arithmetic with two')
print('monomials, assuming that conditions are complied.')
print('')
print('*** MONOMIAL 1 ***')
print('Write the coefficient 1: ', end='')
c1 = float(input())
print('Write the exponent 1: ', end='')
e1 = int(input())
print('')
M1 = Monomial(c1, e1)
print('*** MONOMIAL 2 ***')
print('Write the coefficient 2: ', end='')
c2 = float(input())
print('Write the exponent 2: ', end='')
e2 = int(input())
print('')
M2 = Monomial(c2, e2)
monomial_sum = None
monomial_difference = None
monomial_product = None
monomial_quotient = None
# Monomial addition: M1 + M2
try:
monomial_sum = M1.add(M2)
print('SUM: ' + str(monomial_sum))
except Exception as e:
print('SUM: Invalid operation.')
# Monomial subtraction: M1 - M2
try:
monomial_difference = M1.subtract(M2)
print('DIFFERENCE: ' + str(monomial_difference))
except Exception as e:
print('DIFFERENCE: Invalid operation.')
# Monomial multiplication: M1 * M2
monomial_product = M1.multiply(M2)
print('PRODUCT: ' + str(monomial_product))
# Monomial division: M1 / M2
try:
monomial_quotient = M1.divide(M2)
print('QUOTIENT: ' + str(monomial_quotient))
except Exception as e:
print('QUOTIENT: Invalid operation.')
print()
print('Write the value to evaluate: ', end='')
value = float(input())
print()
print('Value of M1 is ' + str(M1.evaluate(value)))
print('Value of M2 is ' + str(M2.evaluate(value)))
if monomial_sum is not None:
print('Value of M1 + M2 is ' + str(monomial_sum.evaluate(value)))
else:
print('Value of M1 + M2 cannot be computed because \
is an invalid operation.')
if monomial_difference is not None:
print('Value of M1 - M2 is ' + str(monomial_difference.evaluate(value)))
else:
print('Value of M1 - M2 cannot be computed because \
is an invalid operation.')
print('Value of M1 * M2 is ' + str(monomial_product.evaluate(value)))
if monomial_quotient is not None:
print('Value of M1 / M2 is ' + str(monomial_quotient.evaluate(value)))
else:
print('Value of M1 / M2 cannot be computed because \
is an invalid operation.')
print('')
print('THANK YOU FOR USING THIS PROGRAM!')
| false |
6f92d75468e99445c071c26daf00dc7392c95ba2 | badilet/Task21 | /Task21.py | 251 | 4.15625 | 4 | # Напишите функцию которая будет суммировать введенные три случайные цифры.
def multiply(num1, num2, num3):
answer = num1 * num2 * num3
return answer
print(multiply(2, 2, 2))
| false |
b0c57e4bbcfa9a9e6283ebceeca1a0a5594a28c5 | ramyashah27/chapter-8-and-chapter-9 | /chapter 9 files are op/03write.py | 382 | 4.15625 | 4 | # f = open('another.txt', 'w')
# f.write("this file is created through writing in 'w'")
# f.close()
# this is to make/open file and will add (write) all data in it, it will overright
f = open('another.txt', 'a')
f.write(' and this is appending')
f.close()
#this is to add data in the end
# how many times we run the program each time the data in write will add in the end | true |
b2c09cf42fa22404a0945b1746176a1b847bd260 | dobtco/beacon | /beacon/importer/importer.py | 974 | 4.125 | 4 | # -*- coding: utf-8 -*-
import csv
def convert_empty_to_none(val):
'''Converts empty or "None" strings to None Types
Arguments:
val: The field to be converted
Returns:
The passed value if the value is not an empty string or
'None', ``None`` otherwise.
'''
return val if val not in ['', 'None'] else None
def extract(file_target, first_row_headers=[]):
'''Pulls csv data out of a file target.
Arguments:
file_target: a file object
Keyword Arguments:
first_row_headers: An optional list of headers that can
be used as the keys in the returned DictReader
Returns:
A :py:class:`~csv.DictReader` object.
'''
data = []
with open(file_target, 'rU') as f:
fieldnames = first_row_headers if len(first_row_headers) > 0 else None
reader = csv.DictReader(f, fieldnames=fieldnames)
for row in reader:
data.append(row)
return data | true |
31d79ed21483f3cbbc646fbe94cf0282a1753f91 | OceanicSix/Python_program | /parallel_data_processing/data_parition/binary_search.py | 914 | 4.125 | 4 | # Binary search function
def binary_search(data, target):
matched_record = None
position = -1 # not found position
lower = 0
middle = 0
upper = len(data) - 1
### START CODE HERE ###
while (lower <= upper):
# calculate middle: the half of lower and upper
middle = int((lower + upper) / 2)
if data[middle]==target:
matched_record=target
position=middle
return position,matched_record
elif data[middle]<target:
lower = middle + 1
else:
upper=middle-1
### END CODE HERE ###
return position, matched_record
if __name__ == '__main__':
D = [55, 30, 68, 39, 1,
4, 49, 90, 34, 76,
82, 56, 31, 25, 78,
56, 38, 32, 88, 9,
44, 98, 11, 70, 66,
89, 99, 22, 23, 26]
sortD=D[:]
sortD.sort()
print(binary_search(sortD,31)) | true |
33e560583b1170525123c867bb254127c920737f | OceanicSix/Python_program | /Study/Search_and_Sort/Insertion_sort.py | 840 | 4.34375 | 4 | # sorts the list in an ascending order using insertion sort
def insertion_sort(the_list):
# obtain the length of the list
n = len(the_list)
# begin with the first item of the list
# treat it as the only item in the sorted sublist
for i in range(1, n):
# indicate the current item to be positioned
current_item = the_list[i]
# find the correct position where the current item
# should be placed in the sorted sublist
pos = i
while pos > 0 and the_list[pos - 1] > current_item:
# shift items in the sorted sublist that are
# larger than the current item to the right
the_list[pos] = the_list[pos - 1]
pos -= 1
# place the current item at its correct position
the_list[pos] = current_item
return the_list | true |
9982e8d147441c02f3bc24a259105ae350477485 | OceanicSix/Python_program | /test/deck.py | 322 | 4.15625 | 4 | def recursive_addition(number):
if number==1:
return 1
else:
return recursive_addition(number-1)+number
print(recursive_addition(4))
def recursive_multiplication(n,i):
if n==i:
return i
else:
return recursive_multiplication(n-1,i)*n
print(recursive_multiplication(5,2)) | false |
f23588e2e08a6dd36a79b09485ebc0f7a59ed6b7 | chiragkalal/python_tutorials | /Python Basics/1.python_str_basics.py | 930 | 4.40625 | 4 | ''' Learn basic string functionalities '''
message = "it's my world." #In python we can use single quotes in double quotes and vice cersa.
print(message)
message = 'it\'s my world.' #Escape character('\') can handle quote within quote.
print(message)
message = """ It's my world. And I know how to save this world
from bad people. This world has peace and happiness. """ #For multiline string
print(message)
print(message[0]) #returns first letter of str(slicing[start_include:end_exclude:difference])
print(dir(message)) #returns all methods that can apply on str
print(message.lower())
print(message.upper())
print(message.count('l'))
print(message.find('w'))
print(message.find('universe'))
new_msg = message.replace('world', 'universe')
print(new_msg)
# print(help(str)) #retuns all string methds descriptions and
# print(help(str.lower)) #you can also specify specific method name like str.lower() | true |
a267ce733dae7638beee46d181d5e4d81a81747e | YXY980102/YXY980102 | /11,运算符-比较运算符.py | 831 | 4.125 | 4 | '''
运算符 描述 实例
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 True。
> 大于 - 返回x是否大于y (a > b) 返回 False。
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 True。
>= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
<= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 True。
注:比较运算符最后返回的只能是bool值(即True和False)
'''
a=10
b=20
# ==等于
print(a==b)
# !=不等于
print(a!=b)
# >大于
print(a>b)
# <小于
print(a<b)
# >=大于等于
print(a>=b)
# <=小于等于
print(a<=b) | false |
be83f2c448015ca8108ba665a057ce30ef3e7ed0 | Lucchese-Anthony/MonteCarloSimulation | /SimPiNoMatplotlib.py | 885 | 4.21875 | 4 | import math
import random
inside = 1
outside = 1
count = 0
def inCircle(x, y):
#function that sees if the coordinates are contained within the circle, either returning false or true
return math.sqrt( (x**2) + (y**2) ) <= 1
while True:
count = count + 1
#random.uniform generates a 'random' number between the given values, for example, 'random.uniform(-1, 1)' generates .21946219
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
#if its in the circle, add one to the amount of points inside the circle
if (inCircle(x, y)):
inside = inside + 1
#and one if the coordinate is not in the circle
else:
outside = outside + 1
#this prints the ratio of coordinates inside the circle with the points outside the circle
#each 100 is printed to reduce the amount of clutter
if count % 100:
print(inside / outside)
| true |
209c616fe9c622b4269bddd5a7ec8d06d9a27e86 | paula867/Girls-Who-Code-Files | /survey.py | 2,480 | 4.15625 | 4 | import json
import statistics
questions = ["What is your name?",
"What is your favorite color?",
"What town and state do you live in?",
"What is your age?",
"What year were you born?"]
answers = {}
keys = ["Name", "Favorite color", "Hometown","Age", "Birthyear"]
all_answers = []
choice = input("Would you like to take a survey? Type yes or no. ")
while choice == "yes": #forever loop
answers = {} # this dictionary used to be outside. The answers would be replaced everytime someone took a survey with the answers of the last survey.
# When answers was put inside the while loop, that didn't happen anymore.
for q in range(len(questions)): #when you use for i in range i = to an interger. When you use for i in list i = to a concept or variable.
response = input(questions[q] +" ") # raw_input is the same as input for now
answers[keys[q]] = response #sets the keys(list) to a value every time you go through the loop
all_answers.append(answers)
choice = input("Would you like to take a survey? Type yes or no. ")
json_file = open("json.json", "w")
index = 0
json_file.write('[\n')
for d in all_answers:
if (index < len(all_answers) - 1): #length is always one more than the index
json.dump(d,json_file) #opening json file then storing all the items (dictionaries/ d) in all_answers
json_file.write(',\n') #writes into json file #'\n' adds a new line or what is known as 'enter' for humans
else: #will be the last index because the index is less than the length not less than or equal to.
json.dump(d, json_file)
json_file.write('\n')
index += 1
json_file.write(']') # .write adds things to a json file.
json_file.close() #closes json file
ages_surveys = []
for a in all_answers:
the_ages = a["Age"] #add the age you find in all_answers to the_ages
the_ages = int(the_ages)
ages_surveys.append(the_ages)
cities = []
for c in all_answers:
city = c["Hometown"]
cities.append(city)
colors = []
for o in all_answers:
color = o["Favorite color"]
colors.append(color)
print(all_answers)
print("The average age of the participants is", statistics.mean(ages_surveys))
print("The city most people live in is ", statistics.mode(cities))
print("The most liked color among the participants is", statistics.mode(colors))
| true |
d3c5e30d763a1126c3075b37562a8c953c0102d7 | damiras/gb-python | /lesson6/task2.py | 1,215 | 4.3125 | 4 | """
Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
Использовать формулу:
длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом,
толщиной в 1 см * число см толщины полотна. Проверить работу метода.
Например: 20м * 5000м * 25кг * 5см = 12500 т
"""
class Road:
def __init__(self, width, length):
self._width = width
self._length = length
def get_mass(self, one_sq_meter_mass, thickness = 1):
return round(self._length * self._width * one_sq_meter_mass * thickness / 1000, 1)
road = Road(20, 5000)
print(road.get_mass(25, 5))
| false |
c2123be019eca85251fbd003ad3894bb51373433 | jacobroberson/ITM313 | /hw2.py | 1,516 | 4.5 | 4 | '''
This program provides an interface for users to select a medium and enter a distance
that a sound wave wil travel. Then the program will calculate and display the time it
takes for the waveto travel the given distance.
Programmer: Jacob Roberson
Course: ITM313
'''
#Intialize variables
selection = 0
medium = ""
air = 1100
water = 4900
steel = 16400
distace = 0
time = 0
#Receive user input
print("Welcome to THE SPEED OF SOUND CALCULATOR")
selection = int(input("\nSelect the medium the wave will be traveling through by "
"entering the corresponding number\nMENU:\n1.) Air\n2.) Water\n"
"3.) Steel\nSELECTION: "))
distance = eval(input("Please enter the distance the sound wave will travel in feet: "))
#Calculation
if(selection == 1 and distance > 0):
medium = "air"
time = distance/air
elif(selection == 2 and distance > 0):
medium = "water"
time = distance/water
elif(selection == 3 and distance > 0):
medium = "steel"
time = distance/steel
elif(distance <= 0):
print("\nERROR:\nPlease rerun the program and enter a distance greater than 0 feet."
"\n\nINVALID OUTPUT:")
else:
print("\nERROR:\nYou have entered an invalid selection. Please rerun the program "
"and enter a valid selection.\n\nINVALID OUTPUT:")
#Output
print("\nThe time it will take a sound wave to travel", distance, "feet through",
medium, "is %.4f" % (time), "seconds")
| true |
fd297908294c04f1aab9e4ac00fe2aab7b7cab03 | GoldCodeSensen/python_exercise | /digui.py | 680 | 4.125 | 4 | #递归算法关键点:1.调用函数自身的行为 2.有停止条件
#下面举一个计算阶乘的例子
def factorial(x):
if x>1:
return x*factorial(x-1)
else:
return 1
print(factorial(10))
#递归举例,计算斐波那契数列
def fabo(x):
if x > 2:
return fabo(x-1)+fabo(x-2)
elif x == 2:
return 1
elif x == 1:
return 1
print(fabo(20))
#用递归解决汉诺塔
def hanoi(n,A,B,C):
if n==1:
print(A,"->",C)
else:
hanoi(n-1,A,C,B)#将n-1个盘由A移动到B
print(A,"->",C)#将第n个盘由A移动到C
hanoi(n-1,B,A,C)#将将n-1个盘由B移动到C
hanoi(4,"A","B","C") | false |
ff62ce4e5ae2d83bed1443584040f831ab8ca9f0 | GoldCodeSensen/python_exercise | /oop_pool.py | 1,246 | 4.4375 | 4 | #类的组合:把类的实例化放在新的类中
class Turtle:
def __init__(self,x):
self.num = x
class Fish:
def __init__(self,x):
self.num = x
class Pool:#类Pool将Turtle类和Fish类实例化,作为自己的元素
def __init__(self,x,y):
self.turtle = Turtle(x)
self.fish = Fish(y)
def print_num(self):
print('There are %d turtles and %d fishes in the pool' %(self.turtle.num,self.fish.num))
A = Pool(10,200)
A.print_num()
#property(属性函数):property(fget,fset,del,doc),注意它的参数顺序
class C:
def __init__(self,size = 10):#构造函数,定义了一个类“C”的变量size
self.size = size
def getsize(self):
return self.size
def setsize(self,x):
self.size = x
def delsize(self):
del self.size
# 用property作为方法装饰器,将类的方法变为和属性一样的操作。
# 好处在于,这种方式保持了对象对外的形式统一;即便要修改类内部内容,也不会影响对外接口
x = property(getsize,setsize,delsize) #经过属性函数的转化,x可以看作类的一个属性
DD= C()
print('size is %d' %(DD.x))
DD.x = 18
print('size is %d' %(DD.x))
| false |
b927d3a715909e49b61a08a9e60390ce6e0f609a | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 3/Aula 16.py | 1,363 | 4.59375 | 5 | """
Listas são definidos por colchetes => []
Listas podem ser mutaveis
Para adicionar valores a uma lista(ao final da lista), utilize o metodo .append(x)
Para adicionar valores em alguma posição selecionada, utilize o metodo .insert(0, x)
# 0 é a posição e x é o valor, nesse caso, os outros valores da lista iriam "andar uma casa para frente"
Para apagar elementos de uma lista, utilize o metodo .pop(x)
# O .pop geralmente é utilizado para apagar o ultimo indice, porém é possível passar parametros para o mesmo
Para apagar um valor dentro de uma lista, utilize o metodo .remove(x)
# x é o valor que deseja apagar
# Em todos os casos de remoção, a lista é arrumada, e o indice que estava na frente do que foi removido,
# pega a posição do antigo indice, ou seja, a contagem dos indices é reposicionada
# Caso tente remover algo que não esteja na lista, acontecera erro, por isso utilize o if. exemplo:
# if 'x' in y:
# y.remove('x')
"""
num = [2, 5, 9, 1]
num[2] = 3 # Troca o valor de 9 para 3
num.append(7) # Adiciona o valor 7 na ultima posição da lista
num.sort(reverse=True) # Mostra a lista em order reversa
num.insert(2, 0) # Adiciona o 0 na posição 2 e jogo os elementos originais para frente
num.pop(2) # Remove o 3º elemento, que se encontra no 2º indice
print(num)
print(f'Essa lista tem {len(num)} elementos')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.